簡體   English   中英

如何在angular2中將變量從子組件模板傳遞到父組件?

[英]How to pass a variable from a child component template to a parent component in angular2?

我已經創建了4個組件。 它們是1.Icon組件2.Toolbar組件3.Design組件和4.Tree組件

圖標組件中,我從css中導入了大約10個圖標,並為其指定了一個值。

工具欄組件中,我已經使用Icon組件渲染了這10個圖標。

在設計和樹模板中,我使用了工具欄組件,但是它將在設計和樹頁面中顯示所有10個圖標。 我只想在設計中顯示一組圖標,在樹中顯示另一組圖標。 有什么方法可以限制應在工具欄組件的“設計”和“樹”中顯示哪些圖標。

Toolbar.component.ts:
import {Component, Input, Output, EventEmitter} from "@angular/core";

@Component({
selector: 'toolbar',
templateUrl: './toolsbar.template.html'
})

export class ToolBar {

@Output() iconClicked: EventEmitter<string> = new EventEmitter<string>();
@Input() page: string;




onClicked(icontype: string): void {
    this.iconClicked.emit(icontype)
}
}

設計Template.html <div class="panel-section"> <div class="row"> <toolbar (iconClicked)="onToolIconClicked($event)" > </toolbar> </div>

Toolabar.template.Html

<div style="float: right">
<tool-icon [id]="'btn-refresh'" [type]="'refresh'" (iconClicked)="onClicked($event)">
<tool-icon>
<tool-icon [id]="'btn-add'" [type]="'add'" (iconClicked)="onClicked($event)">
<tool-icon>
<tool-icon [id]="'btn-edit'" [type]="'edit'" (iconClicked)="onClicked($event)">
<tool-icon>
<tool-icon [id]="'btn-delete'" [type]="'delete'" (iconClicked)="onClicked($event)">
<tool-icon>
<tool-icon [id]="'btn-import'" [type]="'import'" (iconClicked)="onClicked($event)">
<tool-icon>

<tool-icon [id]="'btn-collapse'" [type]="'collapse'" (iconClicked)="onClicked($event)">
<tool-icon>
<tool-icon [id]="'btn-expandall'" [type]="'expandall'" (iconClicked)="onClicked($event)">
<-tool-icon>
<tool-icon [id]="'btn-expanddiff'" [type]="'expanddiff'" (iconClicked)="onClicked($event)">
<tool-icon>
<tool-icon [id]="'btn-selectall'" [type]="'selectall'" (iconClicked)="onClicked($event)">
<tool-icon>
<tool-icon [id]="'btn-selectnone'" [type]="'selectnone'" (iconClicked)="onClicked($event)">
<tool-icon>
 tool-icon [id]="'btn-selectdiff'" [type]="'selectdiff'" (iconClicked)="onClicked($event)">
<tool-icon>

但是我只想在設計頁面中渲染任何2個圖標。 請提供一些建議

在用於傳遞的角度2中,通過具有輸出屬性和EventEmitter的事件使用從子組件到父組件的變量,該事件實現了可觀察的模式。

您在子組件中聲明輸出屬性的示例

@Output() onProductSelected: EventEmitter<any>;

並在模板的父組件中

<child-product (onProductSelected)=setProduct($event)></child-product>

其中$ event是您要傳遞給父組件的值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM