angular使用@input子组件获取父组件的数据和方法

1使用@input传递数据

1、父组件使用自组件app-header传入msg数据。

 

<app-header [msg]="msg"></app-header>

2、子组件引入 Input 

import { Component, OnInit ,Input } from '@angular/core';

3、子组件中 @Input msg:string 接收父组件传过来的数据

export class HeaderComponent implements OnInit {
@Input() msg:string
constructor() { }
ngOnInit() {
}
}

4、子组件使用父组件的数据

{{msg}}

2使用@input传递数据

实现子组件调用父组件的方法

1、父组件定义方法

run(){
alert('这是父组件的 run 方法');
}

2、在使用自组件是传递方法 run()

<app-header [msg]="msg" [run]="run"></app-header>

3、子组件接收父组件的方法并使用过

export class HeaderComponent implements OnInit {
@Input() msg:string;
@Input() run:any;
constructor() { }
ngOnInit() {
this.run(); /*子组件调用父组件的 run 方法*/
}
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Angular中的@Input和@Output是用来实现组件之间通信的注解。 @Input用来接收组件传递过来的数据,而@Output则用来向组件传递数据。 下面是它们的使用方法: 1. @Input组件使用@Input注解来接收组件传递的数据。例如: ``` import { Component, Input } from '@angular/core'; @Component({ selector: 'child-component', template: ` <div>{{data}}</div> ` }) export class ChildComponent { @Input() data: string; } ``` 在组件使用属性绑定的方式将数据传递给组件。例如: ``` import { Component } from '@angular/core'; @Component({ selector: 'parent-component', template: ` <child-component [data]="myData"></child-component> ` }) export class ParentComponent { myData = 'Hello world'; } ``` 2. @Output 在组件使用@Output注解来定义一个事件。例如: ``` import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'child-component', template: ` <button (click)="onClick()">Click me</button> ` }) export class ChildComponent { @Output() clicked = new EventEmitter<void>(); onClick() { this.clicked.emit(); } } ``` 在组件使用事件绑定的方式监听组件的事件。例如: ``` import { Component } from '@angular/core'; @Component({ selector: 'parent-component', template: ` <child-component (clicked)="onChildClicked()"></child-component> ` }) export class ParentComponent { onChildClicked() { console.log('Child component clicked'); } } ``` 这样就实现了组件组件传递数据的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值