angular组件知识点总结
组件交互
- 通过输入型绑定把数据从父组件传到子组件
// hero-child.component.ts @Input() hero!: Hero; @Input('master') masterName = '';// 起别名,但是不推荐 // hero-parent.component.ts - 通过 setter 截听输入属性值的变化
@Input()get name(): string { return this._name; }set name(name: string) {this._name = (name && name.trim()) || '';}private _name='' - 用ngOnChanges()监听属性值的变化
ngOnChanges(changes: SimpleChanges) {for (const propName in changes) {const changedProp = changes[propName];const to = JSON.stringify(changedProp.currentValue);if (changedProp.isFirstChange()) {console.log(`Initial value of ${propName} set to ${to}`);} else {const from = JSON.stringify(changedProp.previousValue);console.log(`${propName} changed from ${from} to ${to}`);}} }
4.父组件监听子组件的事件
// child
template: `{{name}}
`
export class VoterComponent {@Input() name = '';@Output() voted = new EventEmitter(); // boolean 为传递对象的类型didVote = false;vote(agreed: boolean) {this.voted.emit(agreed);this.didVote = true;}
}
// parent
template: `Should mankind colonize the Universe?
Agree: {{agreed}}, Disagree: {{disagreed}}
// 以$event为传递的值
`
export class VoteTakerComponent {agreed = 0;disagreed = 0;voters = ['Narco', 'Celeritas', 'Bombasto'];onVoted(agreed: boolean) { // agreed 为攒底的对象if (agreed) {this.agreed++;} else {this.disagreed++;}}
}
5.父组件调用子组件方法
template: `Countdown to Liftoff (via local variable)
{{timer.seconds}}
`
// 2.
@ViewChild(CountdownTimerComponent) private timerComponent!: CountdownTimerComponent;
start() { this.timerComponent.start(); }
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
