【问题标题】:click event from component to component从组件到组件的单击事件
【发布时间】:2019-04-24 05:44:47
【问题描述】:

我想通过子组件点击将uuid从父级传递给子级

App.component.ts

import { Component } from '@angular/core';
import { v4 as uuid } from 'uuid';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent  { 

list: string[] = [];

gen() {
 this.list.push(uuid());
 }
}

Child.component.ts

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

@Component({
selector: 'my-child',
templateUrl: './child.component.html'
})

export class ChildComponent  {
 @Input() lists;
 @Input() gens(){};
}

Child.component.html

<button (click)="gens()">Generate</button>
<table border='2'>
 <tr *ngFor="let id of lists"> 
  <td> {{ id }} </td> 
 </tr>
</table>

App.component.html

<my-child [lists]='list' [gens]='gen()'></my-child>

【问题讨论】:

  • 如果你想将数据从孩子传递给父母或父母给孩子,你应该使用 Observable 或 Output 而不是 Intput
  • 好的,但实际上我对这个点击事件很困惑。请您编辑此代码作为答案@ram12393
  • 这也有效,但生成 2 次​​span>

标签: angular


【解决方案1】:

试试这个:

Child.component.html:

<button (click)="gens()">Generate</button>

Child.component.ts:

 @Input() getUuid: any;
  @Output() clickedValue = new EventEmitter(false);

    gens() {
      this.clickedValue .emit(true);
    }

App.component.html:

<my-child [lists]='list' (clickedValue)="onClickedValue($event)" [getUuid]="uuid" ></my-child>

App.component.ts:

uuid: any;
onClickedValue(event) {
  if(event) this.uuid = //write the code for assigning your uuid 
}

【讨论】:

    猜你喜欢
    • 2020-01-06
    • 1970-01-01
    • 2022-11-25
    • 2019-03-20
    • 2017-06-27
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多