首页 > 解决方案 > Angular 9 - 父级中的多个子级

问题描述

有人可以向我解释一下,为什么相应的子开关无法正确更新?单击第二个孩子,第一个孩子更新,但控制台显示正在调用的正确方法。不能像我一样在父组件中调用同一个子组件吗?

https://stackblitz.com/edit/angular-ivy-ch65ks

标签: htmlangulartypescript

解决方案


https://stackblitz.com/edit/angular-ivy-ch65ks

此处添加的答案:child.component.html

<input type="checkbox" id="toggle-button-checkbox_{{inputId}}" [disabled]="isDisabled">
<label class="toggle-button-switch" for="toggle-button-checkbox_{{inputId}}" (click)="toggleCheck()"></label>
<div class="toggle-button-text">
    <div class="toggle-button-text-on">{{textOne}}</div>
    <div class="toggle-button-text-off">{{textTwo}}</div>
</div>

child.component.ts

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss'],
   inputs: ['textOne', 'textTwo', 'checkedValue', 'isDisabled','inputId'],
  outputs: ['checkToEmit']
})
export class ChildComponent implements OnInit {
checkToEmit = new EventEmitter<boolean>();
  textOne: string;
  textTwo: string;
  inputId;
  checkedValue: boolean;
  isDisabled: boolean = false;
  constructor() { }
  ngOnInit(): void {
    console.log(this.checkedValue);
   }
  toggleCheck() {
    this.checkedValue = !this.checkedValue;
    this.checkToEmit.emit(this.checkedValue);
  }
}

父组件.html

<app-child name="one" textOne="Yes" textTwo="No" [checkedValue]="test1" (checkToEmit)="test1Checked($event)" inputId="1">
</app-child>

<app-child name="two" textOne="Yes" textTwo="No" [checkedValue]="test2" (checkToEmit)="test2Checked($event)" inputId="2">
</app-child>  

推荐阅读