问题描述
假设我有4个复选框。
<mat-checkbox>1</mat-checkbox>
<component-1></component-1>
<mat-checkbox>2</mat-checkbox>
<component-2></component-2>
<mat-checkbox>3</mat-checkbox>
<component-3></component-3>
<mat-checkbox>4</mat-checkbox>
<component-4></component-4>
每个mat-checkbox
都有自己单独的component
。
当用户选中前三个复选框中的任何一个时,它将显示/加载该组件,但是如果用户选中了第四个mat-checkbox
,则它将取消选中上述三个mat-checkbox
,导致其组件隐藏并仅显示第四个组件
案例1:-用户可以一起检查前三个。
案例2:-用户可以检查前三个或第四个。
解决方法
Live example
如果我无意中遗漏了任何东西,请告诉我。
我是这样实现的:
主应用程序模板:
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<mat-checkbox #checkOne (change)="OnChkChanged(1)">1</mat-checkbox>
<component-1 *ngIf="showOne"></component-1>
<mat-checkbox #checkTwo (change)="OnChkChanged(2)">2</mat-checkbox>
<component-2 *ngIf="showTwo"></component-2>
<mat-checkbox #checkThree (change)="OnChkChanged(3)">3</mat-checkbox>
<component-3 *ngIf="showThree"></component-3>
<mat-checkbox #checkFour (change)="OnChkChanged(4)">4</mat-checkbox>
<component-4 *ngIf="showFour"></component-4>
主应用程序组件:
import { Component,VERSION,ViewChild,ElementRef } from "@angular/core";
@Component({
selector: "my-app",templateUrl: "./app.component.html",styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular " + VERSION.major;
@ViewChild("checkOne") checkOne: ElementRef;
@ViewChild("checkTwo") checkTwo: ElementRef;
@ViewChild("checkThree") checkThree: ElementRef;
@ViewChild("checkFour") checkFour: ElementRef;
showOne = false;
showTwo = false;
showThree = false;
showFour = false;
OnChkChanged(id: number) {
if (id === 1) {
this.showOne = !this.showOne;
}
if (id === 2) {
this.showTwo = !this.showTwo;
}
if (id === 3) {
this.showThree = !this.showThree;
}
if (id === 4) {
this.showFour = !this.showFour;
if (this.showFour === true) {
this.uncheckAllThree();
}
}
}
uncheckAllThree() {
this.checkOne["checked"] = false;
this.showOne = false;
this.checkTwo["checked"] = false;
this.showTwo = false;
this.checkThree["checked"] = false;
this.showThree = false;
}
}
ComponentOne:
import { Component } from '@angular/core';
@Component({
selector: 'component-1',template: '<h3>I am Component 1</h3>',})
export class ComponentOne {
}
ComponentTwo:
import { Component,VERSION } from '@angular/core';
@Component({
selector: 'component-2',template: '<h3>I am Component 2</h3>',})
export class ComponentTwo {
}
ComponentThree:
import { Component,VERSION } from '@angular/core';
@Component({
selector: 'component-3',template: '<h3>I am Component 3</h3>',})
export class ComponentThree {
}
ComponentFour:
import { Component,VERSION } from '@angular/core';
@Component({
selector: 'component-4',template: '<h3>I am Component 4</h3>',})
export class ComponentFour {
}
,
我从问题中了解到,前三个复选框对第四个复选框没有影响,但是第四个复选框对以上三个复选框都具有影响。
解决方案:
单击第四个复选框时,您必须使用@Output()将事件传递给父组件,然后您可以在其中具有其他复选框的三个独立组件中使用属性或调用方法。
如果要处理来自父级的数据,则必须更改属性;如果要处理每个组件中的数据,则必须调用方法。
如果您听不懂我在说什么,那么如果您可以在https://stackblitz.com/中向我们展示您的工作示例,那就太好了
P.S:可能有多种解决方案。