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("# ----- 子组件的打印值")
}

}

猜你喜欢

转载自www.cnblogs.com/lihong-123/p/10006014.html