父组件给子组件传值,子组件通过 @input 绑定属性设置输入类型数据

  1. // 父组件
  2. <app-hello [name]="'zhangsan'" [age]="20"></app-hello>
  3. // 子组件
  4. export class HelloComponent implements AfterViewInit {
  5. // 接收的名字和属性的名字一直,不需要在 @Input('name') 标记,否则需要写上
  6. @Input() name: string = ""
  7. @Input() age: number = 0
  8. constructor() { }
  9. ngAfterViewInit(): void { }
  10. }
  11. // 页面使用
  12. <div>{{ name }}</div>
  13. <div>{{ age }}</div>
  • 注意:在属性的外面加 [] 表示绑定动态值,在组件内接收后是布尔类型,不加 [] 表示绑定普通值,在组件内接收后是字符串类型

    通过 ViewChild 获取子组件实例,获取子组件数据

    ```typescript // 父组件

export class HomeComponent implements OnInit { constructor() { } ngOnInit(): void { }

  1. @ViewChild('titleDom') child: any
  2. addFun(){
  3. // 直接操作子组件的方法和数据
  4. this.child.parentFunChild()
  5. }

}

// 子组件 export class TitleComponent implements OnInit { constructor() { } ngOnInit(): void { }

  1. parentFunChild(){
  2. console.log('父组件操作子组件的数据方法')
  3. }

} ```