@input* 和@output方式
1.方便实现父子组件的双向绑定
father.component.ts
import { Component } from '@angular/core'
@Component({
selector: 'app-father',
template: `<h1>hello:{{viewdata}}<app-attr [(name)]='viewdata' ></app-attr></h1>`,
})
export class fatherComponent{
viewdata:String = '默认值';
constructor(){
}
}
子组件`
attr.component.ts
mport { Component,Input,EventEmitter,Output} from '@angular/core'
@Component({
selector: 'app-attr',
template: '<button (click)="open()">点击</button><span>{{name}}</span>',
})
export class attrComponent{
@Input() name: string;
@Output() nameChange: EventEmitter<any> = new EventEmitter();//必须以xxxChange向外发射事件
constructor(){
console.log(this.name)
}
open(){
let value = window.prompt("请输入")
this.nameChange.emit(value)
}
}
//可以通过【methods】 = 'fn' 传递方法
模板中通过@viewchild方式
父组件
直接使用
import { Component } from '@angular/core'
@Component({
selector: 'app-father',
template: `<app-attr [(name)]='viewdata' #child></app-attr></h1>
<hr>
<p>{{child.childAttr}}</p>`
})
export class fatherComponent{
}
通过@viewchild 方式
import { Component ,ViewChild} from '@angular/core'
@Component({
selector: 'app-father',
template: `<h1>hello:{{viewdata}}age:{{age}}<app-attr [(name)]='viewdata' #child></app-attr></h1>
<hr>
<p>{{child.childAttr}}</p>
<button (click)='getChildValue()'>子组件</button>
`,
})
export class fatherComponent{
@ViewChild('child', {static: false}) child: any;
constructor(){
}
getChildValue() {
console.log(this.child.childAttr); // 通过这种方式可以获取到子组件的方法和属性值
}
}