本文共 3192 字,大约阅读时间需要 10 分钟。
在angular组件中数据交互主要有下面几种
//父组件html
子组件中通过emit将要传递出去的参数传递给父组件,父组件中就可以获取到
在angular中使用局部模板变量可以获取到子组件的实例引用
模板局部变量的定义是使用#name
//父组件html代码
@ViewChild
获取子组件的引用这种方法跟使用模板局部变量一样的,都是在父组件中调用子组件的方法
子组件跟上面方法一样的//父组件ts文件dataSet = [ { "id":0,"name":"张三"}, { "id":1,"name":"李四"} ] //@ViewChild(子组件名称) 随便命名:子组件名称 @ViewChild(ChildComponent) child:ChildComponent; father(){ //调用子组件方法 this.child.childFn(); }//父组件html代码
中间人模式就是第一种方式的改版,如果两个组件没有父子关系,那么久查找他们共同的父组件,我们知道angular是有一个根组件组成的组件树,那么至少有根组件可以使用的。
com1
点击按钮传递参数到组件com2
中 具体代码如下: //com1组件html代码//com1组件ts代码//创建一个输出@Output()outcom1Fn = new EventEmitter我是com1组件
();com1Fn(){ this.outcom1Fn.emit("我是com1组件的");}//根组件作为中间者模式代码//中间者ts文件private com1Tocom2;//根组件作为中间者appFn(event:any){ console.log(event); this.com1Tocom2 = event;}//中间者html代码 //com2组件ts代码@Input() com2:string = "";//com2组件的html代码 我是com2组件
我是com1组件传递过来的:{
{com2}}
总结说明:angular项目有时候运行没效果,自己觉得代码没错,那么请重启下服务
在父组件传递数据到子组件中,子组件接受数据,可以对其接收的数据进行处理后再显示在页面中,这里就要用到
set
与get
方法
//父组件ts文件,传递一个parent给子组件data:string = "parent";//父组件html代码
//子组件ts文件export class Comdemo01Component implements OnInit { _input: string; @Input() public set input(v: string) { this._input = v.toUpperCase();//转换大写输出 console.log(v); } public get input(): string { return this._input; } constructor() { } ngOnInit() { }}//子组件html代码I am fron { {input}}
//父组件ts文件import { Component, OnInit } from '@angular/core';@Component({ selector: 'app-father1', templateUrl: './father1.component.html', styleUrls: ['./father1.component.css']})export class Father1Component implements OnInit { constructor() { } public name:string = "我是父组件的名字"; public dataSet:Array= [ { "id":"0","name":"张三"}, { "id":"1","name":"李四"}, { "id":"2","name":"王五"} ] ngOnInit() { }}
//子组件ts文件import { Component, OnInit } from '@angular/core';import {Father1Component} from "app/father1/father1.component";@Component({ selector: 'app-child1', templateUrl: './child1.component.html', styleUrls: ['./child1.component.css']})export class Child1Component implements OnInit { constructor(private father1:Father1Component) { } ngOnInit() { }}
//子组件html代码{
{ father1.name}}