angular6–组件交互

  • Post author:
  • Post category:其他


组件交互是指让两个或多个组件之间共享信息的方法

一:数据传递:

1通过输入型绑定把数据从父组件传到子组件 @Input属性绑定

属性绑定用于父组件向子组件传递数据。子组件可以采用以下两种方式获取属性的变更:

2父组件监听子组件的事件  @Output事件绑定

事件绑定用于子组件向父组件触发事件,将子组件的信息传给父组件,父组件通过绑定的处理函数处理事件。

举例:子组件

import { Component, EventEmitter, Input, Output } from ‘@angular/core’;

@Component({


selector: ‘

app-voter

‘,

template: `

<h4>{

{name}}</h4>

<button (click)=”search(true)”  [disabled]=”didVote”>Agree</button>

<button (click)=”vote(false)” [disabled]=”didVote”>Disagree</button>

`

})

export class VoterComponent {



@Input()  name: string;



@Output() voted = new EventEmitter<any>();


didVote = false;

search(agreed: boolean) {



this.voted.emit(agreed);


this.didVote = true;

}

}

父组件:

import { Component }      from ‘@angular/core’;

@Component({


selector: ‘app-vote-taker’,

template: `

<

app-voter

*ngFor=”let voter of voters”


[name]=”voter”

(voted)=”onSearch($event)”

>

<

/app-voter

>               注意L:这里的<

app-voter

>   <

/app-voter

> 是子组件,把子组件放到父组件里用

`

})

export class VoteTakerComponent {


agreed = 0;

disagreed = 0;

voters = [‘Mr. IQ’, ‘Ms. Universe’, ‘Bombasto’];


onVoted(agreed: boolean) {


agreed ? this.agreed++ : this.disagreed++;

}


}

二:父组件调用子组件属性和方法

1父组件与子组件通过

本地变量

互动  #a

父组件在模板中采用模板局部变量访问子组件属性或方法

子组件:

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

@Component({
  selector: 'app-child1',
  templateUrl: './child1.component.html',
  styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  greeting(name: string) {
    console.log("hello" + name);
  }

}

父组件:

<app-child1 #child1> </app-child1>
<button (click)="child1.greeting('Jerry')">调用child2的greeting方法</button>

这个

本地变量

方法是个简单便利的方法。但是它也有局限性,因为父组件-子组件的连接必须全部在父组件的模板中进行。父组件本身的代码对子组件没有访问权。

2父组件调用

@ViewChild()

父组件:放到类里

@ViewChild('child1')
child1:Child1Component; //父组件中获得子组件的引用

ngOnInit(){
  this.child1.greeting("Tom");
}

三非父子组件通过服务来通信

如果需交互的组件间没有父子层级关系,则可以通过注入同一服务实例,通过服务实现信息交互。注意,由于注入层级问题,该服务实例必须至少注入在共同祖先之上。

详情见

https://mp.csdn.net/postedit/81271397



版权声明:本文为qq_38643776原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。