Angular6父子组件的传值问题总结

一.父组件向子组件传数据

<!-- 将userName的值通过[name]属性传给子组件 -->

<!-- 父组件html -->
<app-child [name]='userName'></app-child>
//父组件ts

//要传的数据userName
userName = 'user1';
//子组件ts
 import { Component,OnInit,Input, Output, EventEmitter} from '@angular/core';
 @Component({
  selector: 'app-child',
  templateUrl: './app-child.component.html'
})
export class AppChildComponent implements OnInit {
 @Input() name:string;
 
  ngOnInit() {
    console.log(this.name)   //'user1'
  }
}
 

二.子组件向父组件传数据

<!-- 子组件html -->
<!-- 子组件发送数据的触发方法 -->
<button (click)="emitNewName()">发送</button>
//子组件ts
 import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
  selector: 'app-child',
  templateUrl: './app-child.component.html'
})
export class AppChildComponent implements OnInit {
  @Output() onNameChanged = new EventEmitter();
  newName = 'newName';
  ngOnInit() {
  }
  emitNewName() {
    this.onNameChanged.emit(this.newName);
  }
}
<!-- 父组件html -->
<app-child (onNameChanged)='nameChanged($event)'></app-child>
//父组件ts
nameChanged(newName){
   console.log(newName);   //'newName'
}

三.父组件获取子组件属性或方法

方法一 (子组件加上属性标记,只能在html中使用,ts中无效).

//子组件ts  定义子组件属性newName 和方法getName()
  newName = 'newName';
  getName(){
    console.log('get it',this.newName);
  }
<!-- 父组件html 访问子组件属性和方法 -->
<app-child #child></app-child>

{{child.newName}}   
<button (click)="child.getName()">点击</button>

方法二.(使用@ViewChild)

//父组件ts
import { Component, OnInit, ViewChild} from '@angular/core';
//引入子组件
import { AppChildComponent } from './components/app-child/app-child.component';  
 
export class AppFatherComponent implements OnInit {
  @ViewChild(AppChildComponent)
  child:AppChildComponent
  
  ngOnInit() {
    console.log(this.child.newName)
    
  }
}

方法三.

//父组件ts
//引入子组件
import { AppChildComponent } from './components/app-child/app-child.component';  
 
export class AppFatherComponent implements OnInit {
 constructor(private appChildComponent :AppChildComponent )
  ngOnInit() {
    console.log(this.appChildComponent.newName)
    
  }
}

//父组件app.father.module.ts  import子组件
@NgModule({
  declarations: [
    AppFatherComponent,
    AppChildComponent
  ],
  imports: [
    AppChildComponent     // ************需要导入
  ]
})
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值