Как по нажатию кнопки менять отобразить один компонент вместо другого. Angular
Пожалуйста, помогите выйти из тупика. У меня есть 4 компонента:
- Две кнопки
- Контейнер
- Красный блок
- Синий блок
Мне нужно сделать так, чтобы
- при нажатии на одну кнопку контейнер очищался от всего что там было и в нём появлялся Красный блок,
- при нажатии на другую - контейнер очищался от всего что там было и в нём появлялся Синий блок.
Вот мой код:
- Кнопки
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'buttons',
// для простоты вынесла шаблон сюда. вообще-то он в отдельном файле
template: `<input type = "button" (click)="redclick()" value = "Show red block">
<input type = "button" (click)="blueclick()" value ="Show blue block">`,
styleUrls: ['./buttons.component.css']
})
export class ButtonsComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
// Две заглушки. В этих функциях должны обрабатываться нажатия на кнопки. Но я не представляю, как.
redclick():void{
alert("Show red block");
}
blueclick():void{
alert("Show red block");
}
}
2.Контейнер. В нём должны отображаться красный и синий блок, в зависимости от нажатой кнопки:
import { Component, OnInit } from '@angular/core';
import {NgModule} from "@angular/core";
@Component({
selector: 'panel',
// я чувствую, что в функциях-заглушках я должна как-то обратиться к ng-content. Но как это сделать?
template: `<div> Panel works!
<ng-content></ng-content>
</div>`,
styleUrls: ['./panel.component.css']
})
export class PanelComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
3.Красный блок:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'redblock',
template: `<div>
<p>redblock works!</p>
</div>`,
styleUrls: ['./redblock.component.css']
})
export class RedblockComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
Синий блок точно такой же, как красный. Только имеет селектор "blueblock" и класс BlueblockComponent
В AppComponent у меня вот что:
import {Component} from '@angular/core';
import {Template} from "@angular/compiler/src/render3/r3_ast";
@Component({
selector: 'my-app',
template: `<buttons></buttons>
<panel></panel>`
})
export class AppComponent{}
Ответы (1 шт):
Автор решения: Alexy
→ Ссылка
Используйте @Input и @Output для принятия/передачи значения и SwitchCase для переключения компонента и EventEmitter для сообщения изменений.
buttons.component.ts
export class ButtonsComponent implements OnInit {
@Output() clickBtn: EventEmitter<string> = new EventEmitter<string>();
constructor() {
}
ngOnInit(): void {
}
onClick(color: string): void {
this.clickBtn.emit(color);
}
}
buttons.component.html
<div class="row">
<div class="col-12">
<button type="button" class="btn btn-danger mr-3" (click)="onClick('red')" >Show red block</button>
<button type="button" class="btn btn-primary" (click)="onClick('blue')">Show blue block</button>
</div>
</div>
color-block.component.html
<div class="p-4">
<ng-content></ng-content>
</div>
color-block.component.ts
export class ColorBlockComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
panel.component.ts
export class PanelComponent implements OnInit {
@Input() colorType: string;
constructor() {
}
ngOnInit(): void {
}
}
panel.component.html
<div class="bg-light p-4 my-4" [ngSwitch]="colorType">
<ng-content></ng-content>
<app-color-block [ngClass]="'bg-red'" *ngSwitchCase="'red'">
<p>red block</p>
<p>some random content</p>
</app-color-block>
<app-color-block [ngClass]="'bg-blue'" *ngSwitchDefault>
<p>blue block</p>
</app-color-block>
</div>
app.component.ts
export class AppComponent {
colorBg = 'blue';
onButtonClick($event: string): void {
this.colorBg = $event;
}
}
app.component.html
<div class="container my-4">
<app-buttons (clickBtn)="onButtonClick($event)"></app-buttons>
<app-panel
[colorType]="colorBg"
>
<p>Panel Works!</p>
</app-panel>
</div>
