2.组件传值 - @ViewChild

2018-10-23  本文已影响0人  嗨姑娘_大个子
一. @ViewChild #name 获取本html页面元素引用


  1. 在html中通过注入属性(#名字)添加引用
<input type="text" #myInput>
  1. 在ts中通过ViewChild获取指定元素
方法一:
import { ViewChild, ElementRef } from '@angular/core';

@ViewChild('myInput') input;  ==> @ViewChild('myInput') input: ElementRef;
ngAfterViewInit() {
    console.dir(this.input);
} 

this.input.nativeElement.focus();  // 获取焦点
方法二:
//触发这个方法就可以通过参数box获取到这个元素
<div #box (click)="fn(box)"></div>  
fn(dom){ console.log(dom)}
二. @ViewChild 父组件获取子组件的方法(引用)

子组件CircleComponent中定义了 getColorRedFun(i)方法,父组件中想调用这个方法。

  1. html中添加标记 #circleComponent
  2. 使用@ViewChild访问子组件
  3. ngAfterViewInit()以后才可以访问到获取的子组件
  4. 就可以通过 this.circleComponent访问子组件中的属性和方法了。(也可以直接在方法中使用 this.自定义引用子组件组件名.方法 的方式使用!)
// --------------html--------------
<page-circle #circleComponent> </page-circle>

// --------------ts--------------
export class HomePage {
    @ViewChild("circleComponent")
    circleComponent: CircleComponent;
    
    ngAfterViewInit() {  
        this.circleComponent.getColorRedFun(4);
    }
}
栗子2:
import { LiveVideoComponent } from '../../components/live-video/live-video.component';

export class PlayBackModelComponent implements OnInit, AfterViewInit {
    //@ViewChild(子组件名称)    随便命名:子组件名称
    @ViewChild(LiveVideoComponent) live: LiveVideoComponent;
}

ngAfterViewInit() { 
    //调用 LiveVideoComponent 内部的 initLiveVideo方法
    this.live.initLiveVideo();  
}
三. 使用 #name 局部变量获取子组件的引用
// 父组件 html 
<li *ngFor="let item of dataSet">
    <app-child [names] = "item" (click)="father.childFn()" #father></app-child>    //使用模板局部变量 #father 调用子组件的方法
</li>

// 父组件 ts
dataSet = [
    {"id":0,"name":"张三"},
    {"id":1,"name":"李四"}
]
// 子组件 html
<span>{{names.name}}</span> 

// 子组件 ts
@Input() names: any = {}
childFn(){
    console.log("我是子类的方法");
}
angular2生命周期钩子函数
  1. 每个接口都有唯一的一个钩子方法,由接口名加上 ng前缀构成的。比如,OnInit接口的钩子方法叫做ngOnInit。
  2. 生命周期的顺序:
上一篇 下一篇

猜你喜欢

热点阅读