Angular2父子组件之间数据传递:局部变量获取子组件

来源:互联网 发布:百度关键词优化 编辑:程序博客网 时间:2024/06/14 04:01

通过@Input和@Output可以实现数据之间的传递,但是无法获取子组件的类属性和类方法,接下来我们通过局部变量方式实现获取子组件其他成员


第一步:定义子组件:

ChildenComponent.ts(子组件)

import {Component} from '@angular/core';

@Component({
selector: 'app-childen',
 templateUrl: './childen.component.html',
 styleUrls: ['./childen.component.css']
})
export class ChildenComponent {

fun1() {
alert('子组件方法');
 }

}

(1).子组件中之定义了一个fun1()方法,提供给父组件调用


第二步:定义父组件
ParentComponent.ts(父组件)

import {Component} from '@angular/core';

@Component({
selector: 'app-parent',
 templateUrl: './parent.component.html',
 styleUrls: ['./parent.component.css']
})

export class ParentComponent {

}

ParentComponent.html

<div class="parent_div">
 <p>父组件</p>
 <div>
   <input type="button" value="调用子组件方法" (click)="chiden.fun1()">
 </div>
 <!---子组件指令 start-->
 <app-childen #chiden></app-childen>
 <!---子组件指令 end-->
</div>

通过#号来标识一个变量, 这样在父组件模板中创建了一个局部变量#chiden来获取子组件的实例,调用子组件中的方法和属性。上面例子中我们定义了#chiden之后,绑定点击就可以调用子组件的方法了


看看效果:点击按钮,弹出子组件方法的alert('子组件方法'); 






个人学习心得,大神路过 ,不喜勿喷
有问题加我微信提问或者留言

阅读全文
0 0
原创粉丝点击