文章内容
2020/5/23 14:57:02,作 者: 黄兵
Angular 父组件向子组件传值
最近有一个需求:在Angular里面,父组件向子组件传值。
子组件代码如下:
component-interaction/src/app/hero-parent.component.ts
import { Component } from '@angular/core'; import { HEROES } from './hero'; @Component({ selector: 'app-hero-parent', template: ` <h2>{{master}} controls {{heroes.length}} heroes</h2> <app-hero-child *ngFor="let hero of heroes" [hero]="hero" [master]="master"> </app-hero-child> ` }) export class HeroParentComponent { heroes = HEROES; master = 'Master'; }
父组件代码如下:
component-interaction/src/app/hero-child.component.ts
import { Component, Input } from '@angular/core'; import { Hero } from './hero'; @Component({ selector: 'app-hero-child', template: ` <h3>{{hero.name}} says:</h3> <p>I, {{hero.name}}, am at your service, {{masterName}}.</p> ` }) export class HeroChildComponent { @Input() hero: Hero; @Input('master') masterName: string; }
双向数据绑定会报错,Can't bind to 'ngModel' since it isn't a known property of 'input'.
解决办法是在app.module.ts的imports加入 FormsModule
参考资料:
3、Angularjs2-Can't bind to 'ngModel' since it isn't a known property of 'input'.
评论列表