angular 中组件中数据传递

@input* 和@output方式

1.方便实现父子组件的双向绑定
father.component.ts

import { Component } from '@angular/core'

@Component({
    selector: 'app-father',
    template: `<h1>hello:{{viewdata}}<app-attr   [(name)]='viewdata' ></app-attr></h1>`,
  })
export class  fatherComponent{
    viewdata:String = '默认值';
    constructor(){
    }
  }
  

子组件`

attr.component.ts

mport { Component,Input,EventEmitter,Output} from '@angular/core'
@Component({
   selector: 'app-attr',
   template: '<button (click)="open()">点击</button><span>{{name}}</span>',
 })
export class  attrComponent{
   @Input() name: string;
   @Output() nameChange: EventEmitter<any> = new EventEmitter();//必须以xxxChange向外发射事件
   constructor(){
       console.log(this.name)
   }
   open(){
       let value = window.prompt("请输入")
       this.nameChange.emit(value)
   }
 }
 //可以通过【methods】 = 'fn' 传递方法

模板中通过@viewchild方式

父组件

直接使用
import { Component } from '@angular/core'

@Component({
    selector: 'app-father',
    template: `<app-attr   [(name)]='viewdata' #child></app-attr></h1>
    <hr>
    <p>{{child.childAttr}}</p>` 
  })
export class  fatherComponent{

  }
通过@viewchild 方式
import { Component ,ViewChild} from '@angular/core'

@Component({
    selector: 'app-father',
    template: `<h1>hello:{{viewdata}}age:{{age}}<app-attr   [(name)]='viewdata'  #child></app-attr></h1>
    <hr>
    <p>{{child.childAttr}}</p>
    <button (click)='getChildValue()'>子组件</button>
    `,
  })
export class  fatherComponent{
    @ViewChild('child', {static: false}) child: any;

    constructor(){

     
    }
    getChildValue() {
      console.log(this.child.childAttr); // 通过这种方式可以获取到子组件的方法和属性值
    }
  }
  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值