父组件给子组件传值,子组件通过 @input 绑定属性设置输入类型数据
// 父组件<app-hello [name]="'zhangsan'" [age]="20"></app-hello>// 子组件export class HelloComponent implements AfterViewInit {// 接收的名字和属性的名字一直,不需要在 @Input('name') 标记,否则需要写上@Input() name: string = ""@Input() age: number = 0constructor() { }ngAfterViewInit(): void { }}// 页面使用<div>{{ name }}</div><div>{{ age }}</div>
- 注意:在属性的外面加 [] 表示绑定动态值,在组件内接收后是布尔类型,不加 [] 表示绑定普通值,在组件内接收后是字符串类型
通过 ViewChild 获取子组件实例,获取子组件数据
```typescript // 父组件
export class HomeComponent implements OnInit { constructor() { } ngOnInit(): void { }
@ViewChild('titleDom') child: anyaddFun(){// 直接操作子组件的方法和数据this.child.parentFunChild()}
}
// 子组件 export class TitleComponent implements OnInit { constructor() { } ngOnInit(): void { }
parentFunChild(){console.log('父组件操作子组件的数据方法')}
} ```
