听话的钢笔 發表於 2019-12-18 23:50:00

angular组件交互

<blockquote>
<p>摘要:本文主要介绍angular组件间的交互,以下将会把七种交互方式代码进行展示,并且分析各种方式所使用的情景。七种交互方式的描述(如"通过输入型绑定把数据从父组件传到子组件"这般)来源于Angular中文网。</p>
</blockquote>
<h2 id="一通过输入型绑定把数据从父组件传到子组件">一、通过输入型绑定把数据从父组件传到子组件</h2>
<h3 id="1适用情景及描述">1.适用情景及描述</h3>
<p>这种方式比较容易理解,一般适用于将父组件中的值传送给子组件进行使用。在父组件中,通过在其引用的子组件标签中使用<code>[]</code>进行单项传值,而在子组件中通过<code>@Input()</code>来接收父组件传过来的值。</p>
<h3 id="2代码实现只展示部分关键代码下同">2.代码实现(只展示部分关键代码,下同)</h3>
<p>app.component.html(父组件html)</p>
<pre><code class="language-html">&lt;!-- 其中 childInputData 为子组件中与@Input关联的变量,
               appInputData 为父组件中需要传到子组件中值 --&gt;
&lt;app-child-input-component ="appInputData"&gt;&lt;/app-child-input-component&gt;
</code></pre>
<p>app.component.ts(父组件ts)</p>
<pre><code class="language-typescript">public appInputData = ['Baidu', 'Alibaba', 'Tencent'];
</code></pre>
<p>child-input-component.html(子组件html)</p>
<pre><code class="language-html">BAT Stroy:
&lt;ul&gt;
&lt;li *ngFor="let data of childInputData"&gt;{{data}}&lt;/li&gt;
&lt;/ul&gt;

</code></pre>
<p>child-input-component.ts(子组件ts)</p>
<pre><code class="language-typescript">@Component({
selector: 'app-child-input-component',
templateUrl: './child-input-component.component.html',
styleUrls: ['./child-input-component.component.css']
})
export class ChildInputComponentComponent {
// 父组件通过 @Input 传值给子组件
@Input() childInputData: any;
}
</code></pre>
<h3 id="3最终效果">3.最终效果</h3>
<p><img src="https://github.com/defaultw/angular-demos/blob/master/component-interaction-demo/src/assets/imag/input.PNG?raw=true"></p>
<h2 id="二通过setter截听输入属性值的变化">二、通过setter截听输入属性值的变化</h2>
<h3 id="1使用情景及描述">1.使用情景及描述</h3>
<p>通过setter截听输入值变化也是使用<code>@Input()</code>从父组件中向子组件传值,与单纯使用<code>@Input()</code>不同的是如果我们可以直接在使用<code>set</code>来对传过来的变量进行操作,并实时的将修改后的值展示出来。</p>
<h3 id="2代码实现">2.代码实现</h3>
<p>app.component.html(父组件html)</p>
<pre><code class="language-html">一天的的工作:
&lt;app-child-set-component *ngFor="let work of appSetterData" ="work"&gt;&lt;/app-child-set-component&gt;

</code></pre>
<p>app.component.ts(父组件ts)</p>
<pre><code class="language-typescript">public appSetterData = ['work', '', 'sleep', '', 'drink'];
</code></pre>
<p>child-set-component.ts(子组件html)</p>
<pre><code class="language-html">{{item}},
</code></pre>
<p>child-set-component.ts(子组件ts)</p>
<pre><code class="language-typescript">import { Component, Input } from '@angular/core';

@Component({
selector: 'app-child-set-component',
templateUrl: './child-set-component.component.html',
styleUrls: ['./child-set-component.component.css']
})
export class ChildSetComponentComponent {
// 通过setter截听输入值的变化
private item = ''; // 定义了一个私有的变量,用来存放父组件传来的值
// 这边方法名childSetter是与父组件html单项绑定的值的那个名字
@Input() set childSetter(temp: string) {
      // 这边当数组中工作内容为空时会塞进去一些奇奇怪怪的东西:)
    this.item = temp.trim() || 'Touch the fish';
}

// 重新为变量赋值
get childSetter(): string {
    return this.item;
}
}
</code></pre>
<h3 id="3最终效果-1">3.最终效果</h3>
<p><img src="https://github.com/defaultw/angular-demos/blob/master/component-interaction-demo/src/assets/imag/setter.PNG?raw=true"></p>
<h2 id="三通过ngonchanges来截听输入属性值的变化">三、通过ngOnChanges()来截听输入属性值的变化</h2>
<h3 id="1-适用情景及描述">1. 适用情景及描述</h3>
<p>使用<code>ngOnChanges()</code>可以监听到属性值的变化,当属性值发生变化是可以出发<code>ngOnChanges()</code>方法,该方法接受当前和上一属性值的 <code>SimpleChanges</code> 对象在 <code>ngOnInit()</code> 之前以及所绑定的一个或多个输入属性的值发生变化时都会调用。</p>
<p>这种方式适用于子组件需要在对父组件所传值发生变化时进行响应的情景,例如: 父组件传给子组件的值是通过异步请求得到的,当直接使用<code>@Input()</code>方式传值给子组件时,若请求还没有完成,那么子组件将得到一个空值,这是就需要使用<code>ngOnChanges()</code>截听父组件传来值的变化,当所传值有变化时再进行下一步操作。</p>
<h3 id="2代码实现-1">2.代码实现</h3>
<p>app.component.html(父组件html)</p>
<pre><code class="language-html">&lt;h4&gt;3.通过ngChanges()截听属性值的变化&lt;/h4&gt;
&lt;input type="text" [(ngModel)]="appInputValue"&gt;
&lt;button (click)="resetInputValue();"&gt;clearLog&lt;/button&gt;
&lt;app-child-ngonchange-component ="appInputValue"&gt;&lt;/app-child-ngonchange-component&gt;
</code></pre>
<p>app.component.ts(父组件ts)</p>
<pre><code class="language-typescript">/**
* 属性装饰器,用于配置一个视图查询。
* 变更检测器会在视图的 DOM 中查找能匹配上该选择器的第一个元素或指令.
* 如果视图的 DOM 发生了变化,出现了匹配该选择器的新的子节点,该属性就会被更新。
*
* 此处用在 通过 ngOnChanges()截听属性值的变化
*/
@ViewChild(ChildNgonchangeComponentComponent, { static: false })
onChangeChild: ChildNgonchangeComponentComponent;

// 通过 ngOnChanges()截听属性值的变化
public appInputValue: string;

resetInputValue() {
this.appInputValue = 'init';
if (this.onChangeChild) {
    this.onChangeChild.clearLog();
    }
}
</code></pre>
<p>child-ngonchange-component.component.html(子组件html)</p>
<pre><code class="language-html">&lt;h5&gt;Change Log&lt;/h5&gt;
&lt;div *ngFor="let log of changeLog"&gt;{{log}}&lt;/div&gt;
</code></pre>
<p>child-ngonchange-component.ts(子组件ts)</p>
<pre><code class="language-typescript">import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';

@Component({
selector: 'app-child-ngonchange-component',
templateUrl: './child-ngonchange-component.component.html',
styleUrls: ['./child-ngonchange-component.component.css']
})
export class ChildNgonchangeComponentComponent implements OnInit, OnChanges {
@Input() inputValue: string;

// 存放修改log
public changeLog: string[] = [];

ngOnChanges(changes: SimpleChanges) {
    for (const proName in changes) {
      if (changes.hasOwnProperty(proName)) {
      // 此处需要判断对象中是否存在key
      const chng = changes;
      const cur = JSON.stringify(chng.currentValue);
      const prev = JSON.stringify(chng.previousValue);
      this.changeLog.push(`${proName}已修改,修改后:${cur},修改前:${prev};`);
      }
    }
}

clearLog() {
    this.changeLog = [];
}

ngOnInit() {}
}
</code></pre>
<h3 id="3最终效果-2">3.最终效果</h3>
<p><img src="https://github.com/defaultw/angular-demos/blob/master/component-interaction-demo/src/assets/imag/ngOnChanges.PNG?raw=true"></p>
<h2 id="四父组件监听子组件的事件">四、父组件监听子组件的事件</h2>
<h3 id="1适用情景及描述-1">1.适用情景及描述</h3>
<p>父组件监听子组件的事件一般用于子组件向父组件传值的情形,通过弹射一个事件将需要的值传出去。这种方式需要通过<code>@Ouput()</code>来实现。</p>
<h3 id="2代码实现-2">2.代码实现</h3>
<p>app.component.html(父组件html)</p>
<pre><code class="language-html">&lt;h4&gt;4.通过 @Output 向父组件弹射事件&lt;/h4&gt;
{{outputEvent}}
&lt;!-- 这边的 (onclick) 事件为 子组件中通过EventEmitter 弹射出来--&gt;
&lt;app-child-output-component (onclick)="appOnClick($event)"&gt;&lt;/app-child-output-component&gt;
</code></pre>
<p>app.component.ts(父组件ts)</p>
<pre><code class="language-typescript">// 通过 @Output 弹射事件到父组件
public outputEvent: string;

appOnClick(isClick: boolean) {
if (isClick) {
    this.outputEvent = '成功';
}
}
</code></pre>
<p>child-output-component.component.html(子组件html)</p>
<pre><code class="language-html">&lt;button (click)="click(true)"&gt;点击&lt;/button&gt;
</code></pre>
<p>child-output-component.ts(子组件ts)</p>
<pre><code class="language-typescript">import { Component, EventEmitter, Output } from '@angular/core';

@Component({
selector: 'app-child-output-component',
templateUrl: './child-output-component.component.html',
styleUrls: ['./child-output-component.component.css']
})
export class ChildOutputComponentComponent {
// 暴露自定义事件onClick()
@Output() onclick = new EventEmitter&lt;boolean&gt;();

click(isClick: boolean) {
    // click普通方法
    this.onclick.emit(isClick); // 向父组件弹射isClick变量,在被点击时候出发
}
}
</code></pre>
<h3 id="3最终效果-3">3.最终效果</h3>
<p>点击之前</p>
<p><img src="https://github.com/defaultw/angular-demos/blob/master/component-interaction-demo/src/assets/imag/output_befor.PNG?raw=true"></p>
<p>点击之后</p>
<p><img src="https://github.com/defaultw/angular-demos/blob/master/component-interaction-demo/src/assets/imag/output_after.PNG?raw=true"></p>
<h2 id="五父组件与子组件通过本地变量互动">五、父组件与子组件通过本地变量互动</h2>
<h3 id="1适用情景及描述-2">1.适用情景及描述</h3>
<p>组件间通过本地变量互动比较简单,主要适用于在父组件的html中调用子组件的公共变量和公共方法。</p>
<h3 id="2代码实现-3">2.代码实现</h3>
<p>app.component.html(父组件html)</p>
<pre><code class="language-html">&lt;h4&gt;5.通过本地变量传参&lt;/h4&gt;
&lt;app-child-value-component #childData&gt;&lt;/app-child-value-component&gt;
子组件中变量:{{childData.localValue}}
&lt;button (click)="childData.localFunction()"&gt;点击修改子组件中变量值&lt;/button&gt;
</code></pre>
<p>child-value-component.ts(子组件ts)</p>
<pre><code class="language-typescript">import { Component } from '@angular/core';

@Component({
selector: 'app-child-value-component',
templateUrl: './child-value-component.component.html',
styleUrls: ['./child-value-component.component.css']
})
export class ChildValueComponentComponent {
// 本地变量
public localValue = 'This is a local value.';

// 本地方法
localFunction() {
    this.localValue = 'Change the local value!';
}
}
</code></pre>
<h3 id="3最终效果-4">3.最终效果</h3>
<p>点击之前</p>
<p><img src="https://github.com/defaultw/angular-demos/blob/master/component-interaction-demo/src/assets/imag/local_befor.PNG?raw=true"></p>
<p>点击之后</p>
<p><img src="https://github.com/defaultw/angular-demos/blob/master/component-interaction-demo/src/assets/imag/local_after.PNG?raw=true"></p>
<h2 id="六父组件调用viewchild">六、父组件调用@ViewChild()</h2>
<h3 id="1适用情景及描述-3">1.适用情景及描述</h3>
<p>区别于使用本地变量的交互方式,使用<code>@ViewChild()</code>将子组件注入到私有属性里面,可以实现在父组件的ts文件中调用子组件的公共方法和公共变量。</p>
<h3 id="2代码实现-4">2.代码实现</h3>
<p>app.component.html(父组件html)</p>
<pre><code class="language-html">&lt;h4&gt;6.通过@ViewChild() 调用子组件方法&lt;/h4&gt;
子组件中变量:{{data.viewChildValue}}
&lt;app-child-viewchild-component #data&gt;&lt;/app-child-viewchild-component&gt;
&lt;button (click)="viewChildClick()"&gt;点击修改子组件中变量值&lt;/button&gt;
</code></pre>
<p>app.component.ts(父组件ts)</p>
<pre><code class="language-typescript">@ViewChild(ChildViewchildComponentComponent, { static: false })
private viewChild: ChildViewchildComponentComponent;

viewChildClick() {
this.viewChild.click();
}
</code></pre>
<p>child-viewchild-component.ts(子组件ts)</p>
<pre><code class="language-typescript">import { Component } from '@angular/core';

@Component({
selector: 'app-child-viewchild-component',
templateUrl: './child-viewchild-component.component.html',
styleUrls: ['./child-viewchild-component.component.css']
})
export class ChildViewchildComponentComponent {
public viewChildValue = 'befor change';
click() {
    this.viewChildValue = 'after change';
}
}
</code></pre>
<h3 id="3最终效果-5">3.最终效果</h3>
<p>点击之前</p>
<p><img src="https://github.com/defaultw/angular-demos/blob/master/component-interaction-demo/src/assets/imag/viewchild_befor.PNG?raw=true"></p>
<p>点击之后</p>
<p><img src="https://github.com/defaultw/angular-demos/blob/master/component-interaction-demo/src/assets/imag/viewchild_after.PNG?raw=true"></p>
<h2 id="七父组件和子组件通过服务通讯">七、父组件和子组件通过服务通讯</h2>
<h3 id="1适用情景及描述-4">1.适用情景及描述</h3>
<p>这种当时一般用于子父组件互相操作同一变量的情况。</p>
<h3 id="2代码实现-5">2.代码实现</h3>
<p>tService.ts(服务)</p>
<pre><code class="language-typescript">import { Injectable } from '@angular/core';
@Injectable()
export class TService {
public info = '';
constructor() {}
setData(value: string) {
    this.info = value;
    console.log('设置:' + value);
}
getData() {
    console.log('获取:' + this.info);
    return this.info;
}
}
</code></pre>
<p>child-service-component.ts(子组件ts)</p>
<pre><code class="language-typescript">import { Component, OnInit } from '@angular/core';
import { TService } from '../service/tService';
@Component({
selector: 'app-child-service-component',
templateUrl: './child-service-component.component.html',
styleUrls: ['./child-service-component.component.css']
})
export class ChildServiceComponentComponent {
constructor(private tService: TService) {}

setChildValue() {
    this.tService.setData('child data show');
}
}
</code></pre>
<p>child-service-component.html(子组件html)</p>
<pre><code class="language-html">&lt;button (click)="setChildValue()"&gt;设置值,准备让父组件接收&lt;/button&gt;
</code></pre>
<p>app.component.ts(父组件ts)</p>
<pre><code class="language-typescript">// 通过service获取子组件中的
getChildData() {
this.serviceChildDate = this.tservice.getData();
}
</code></pre>
<p>app.component.html(父组件html)</p>
<pre><code class="language-html">&lt;h4&gt;7.通过 服务实现 子父组件通讯&lt;/h4&gt;
父组件接收子组件设置的值:{{serviceChildDate}} &lt;br /&gt;
&lt;app-child-service-component&gt;&lt;/app-child-service-component&gt;
&lt;button (click)="getChildData()"&gt;获取子组件中值&lt;/button&gt;
</code></pre>
<h3 id="3最终效果-6">3.最终效果</h3>
<p>点击之前</p>
<p><img src="https://github.com/defaultw/angular-demos/blob/master/component-interaction-demo/src/assets/imag/service_befor.PNG?raw=true"></p>
<p>点击之后</p>
<p><img src="https://github.com/defaultw/angular-demos/blob/master/component-interaction-demo/src/assets/imag/service_after.PNG?raw=true"></p>
<h2 id="八参考文献">八、参考文献</h2>
<p> Angular组件之间的交互</p>
<p> Angular中文网</p>
<p>本文完整代码请查看github,如果需要更加方便的查看github中代码可以使用在线编辑。</p><br><br>
来源:https://www.cnblogs.com/otblog/p/angular.html
頁: [1]
查看完整版本: angular组件交互