1. 程式人生 > >angular2 2種方式----獲取子元件的類屬性和類方法

angular2 2種方式----獲取子元件的類屬性和類方法

1)-------方法
-----父html檔案
<button (click)="onclickchildfun()">通過@ViewChild呼叫子元件方法</button>
----父ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { childComponent } from './childView/child.component';
@Component({
selector: 'logoSing',
templateUrl: './logoSing.html',
styleUrls: ['./logoSing.css']
})
export class LogoSingComponent implements OnInit {
@ViewChild(childComponent) child: childComponent;//這裡傳入一個子元件例項引入,定義了一個變數child接收
onclickchildfun(){//呼叫子元件方法
this.child.func()
}
}
-----子ts
import {Component, Output, EventEmitter,OnInit} from '@angular/core';
@Component({
selector: 'child-Component',
templateUrl: './child.component.html',
styleUrls: ['./child.component.less']
})

export class childComponent implements OnInit {
func(){
console.log("ViewChild ----- 子元件的列印值")
}

}

2)-----方法

----父html檔案
<button (click)="child.func()">通過#號呼叫子元件方法</button>
<child-Component #child></child-Component>//通過#號來標識一個變數, 這樣在父元件模板中建立了一個區域性變數#chiden來獲取子元件的例項,
呼叫子元件中的方法和屬性

----父ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { childComponent } from './childView/child.component';
@Component({
selector: 'logoSing',
templateUrl: './logoSing.html',
styleUrls: ['./logoSing.css']
})
export class LogoSingComponent implements OnInit {

}
-----子ts
import {Component, Output, EventEmitter,OnInit} from '@angular/core';
@Component({
selector: 'child-Component',
templateUrl: './child.component.html',
styleUrls: ['./child.component.less']
})

export class childComponent implements OnInit {
func(){
console.log("# ----- 子元件的列印值")
}

}