美文网首页
ng4.x 父组件传值 / 方法给子组件--@Input + @

ng4.x 父组件传值 / 方法给子组件--@Input + @

作者: __凌 | 来源:发表于2017-10-23 16:46 被阅读0次

# 1: @Input


步骤:

1:父组件调用子组建时传入值/方法

2:在子组件引入Input模块

3:在子组件声明,通过@Input接受父组件传过来的数据/方法

4:在子组件使用父组件传过来的数据/方法



《parent.component.html》:【父】

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

《child.component.ts》:【子】

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

...   ...

export class HeaderComponent implement OnInit {

@Input() msg:string;

@Input() run;

constructor() { }

ngOnInit() { }

}

parent.component.ts》:

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

export class NewsComponent implements OnInit {

public msg = "这是父组件的数据";

constructor(){}

...    ...

run() {

  alert("这是父组件的方法");

《child.component.html》:

<h2>  这是父组件传来的值: {{ msg }}</h2>

<button (click)="run()">接受父组件传来的方法</button>


# 2: @Output


步骤:

1:子组件引入Output 和 EventEmitter

2:子组件中实例化 EventEmitter

3:子组件通过EventEmitter对象outer实例广播数据

4:父组件调用子组件的时候,定义接受事件

《parent.component.html》:

<app-child (toparent)="resuestData($event)"></app-child>

《child.component.html》:

<button (click) = "requersData()">执行父组件的方法 通过@Output</button>

《child.component.ts》:

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

...   ...

export class HeaderComponent implement OnInit {

@Input() msg:string;

@Input() run;

@Output() private toparent = new EventEmitter<string>();

constructor() { }

ngOnInit() { }

requestData(){

     this.toparent.emit('这是子组件传的值');

}

}

parent.component.ts》:

export class NewsComponent implements OnInit {

public msg = "这是父组件的数据";

public list = [];

constructor(private http:Http){  }

...    ...

requestData(e){

console.log(e);

var _that=this;

var url ="***";

this.http.get(url).map(res=>res.json()).subscribe(function(data){

console.log(data);

},function(err){

console.log(err);

})

}


相关文章

  • 父子组件传值@Input @Output @ViewChild

    一、父组件给子组件传值 -@Input 父组件调用子组件 的时候传入数据 子组件引入 Input 模块 子组件中 ...

  • react-父子组件间通信

    React-父子组件间通信 父组件传 值 给子组件, 传 方法 给子组件 子组件接收 值 ,触发父组件的 方法

  • Angular 8 父子组件之间通信(简单易懂)

    父组件给自组件传值 - @input 父组件不仅可以给子组件传递简单的数据,还可以把自己的方法以及整个父组件传给子...

  • Vue_组件间传值

    1、父组件传值给子组件2、子组件传值给父组件 1、父组件传值给子组件 2、子组件传值给父组件

  • 2018-09-05

    组件传值问题 父组件给子组件传值应该使用props。子组件要给父组件传值,需要调用父组件传递的方法。props传值...

  • vue2.0 父子组件传值

    父组件传值给子组件 子组件 子组件通过 props 接收值 父组件 父组件通过标签属性传值 子组件传值给父组件 子...

  • VUE组件之间传值

    1.父组件传值给子组件 父组件image.png 子组件image.png 2.子组件传值给父组件 方法1: 子组...

  • vue组件间参数与事件传递

    父组件向子组件传值 以及父组件调用子组件方法 子组件向父组件传值 以及子组件触发调用父组件方法

  • react子组件、父组件相互传值

    子组件传图片路径imgUrl值给父组件,父组件传imgaddr值给子组件子组件: 父组件:

  • 子组件向父组件传值

    子组件向父组件传值 思路:子组件向父组件传值,可以通过调用父组件的方法,来变相的传值 父组件向子组件传递方法 父元...

网友评论

      本文标题:ng4.x 父组件传值 / 方法给子组件--@Input + @

      本文链接:https://www.haomeiwen.com/subject/aerauxtx.html