View钩子

来源:互联网 发布:公司网络营销策划书 编辑:程序博客网 时间:2024/06/04 17:52

1.父组件调用子组件的方法

(1)子组件的控制器

export class TreeChildComponent implements OnInit {  constructor() { }  ngOnInit() {  }  greeting(name:string){    console.log('hello'+name)  }}

(2)父组件调用

A.模板

<app-tree-child #child1></app-tree-child>
B控制器调用子组件方法

import { Component, ViewChild, OnInit } from '@angular/core';import { StockInfo } from './search-stock/search-stock.component';import { TreeChildComponent } from './tree-child/tree-child.component';@Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: ['./app.component.css']})export class AppComponent implements OnInit {   //声明一个变量child1,通过@ViewChild()装饰器获得对子组件的引用 @ViewChild("child1") child1:TreeChildComponent;  constructor(){      }  ngOnInit(): void {    this.child1.greeting('tom');  }}
C.父组件模板直接调用子组件方法

<app-tree-child #child2></app-tree-child><button (click)="child2.greeting('jerry')">调用child2的greeting方法</button>

2.AfterViewInitAfterViewChecked

(1)在父组件上实现 AfterViewInitAfterViewChecked接口,组件模板所有内容组装完成以后,已经给用户看了以后,这两个钩子才被调用

 ngAfterViewChecked(): void {    console.log("父组件的视图变更检测完成");  }  ngAfterViewInit(): void {    console.log("父组件的视图初始化完成");  }


(2)同样,在子组件中也实现这两个钩子

 ngAfterViewChecked(): void {    console.log("子组件的视图变更检测完成");  }  ngAfterViewInit(): void {    console.log("字组件的视图初始化完成");  }

(3)父组件中调用子组件方法

ngOnInit(): void {    setInterval(()=>{      this.child1.greeting('tom');    },5000)     }

注意:

(1)组件有子组件,只有子组件的视图组装完毕以后,父组件的这两个方法才会被调用

(2)如果要在这两个方法中改变某个值,要写在一个timeout里面,否则会抛出异常