0

Пожалуйста, помогите выйти из тупика. У меня есть 4 компонента:

  1. Две кнопки
  2. Контейнер
  3. Красный блок
  4. Синий блок

Мне нужно сделать так, чтобы

  1. при нажатии на одну кнопку контейнер очищался от всего что там было и в нём появлялся Красный блок,
  2. при нажатии на другую - контейнер очищался от всего что там было и в нём появлялся Синий блок.

Вот мой код:

  1. Кнопки
 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 {
          }
        }
  1. Синий блок точно такой же, как красный. Только имеет селектор "blueblock" и класс BlueblockComponent

  2. В 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. Вот как выглядит страница. введите сюда описание изображения

1 ответ 1

0

Используйте @Input и @Output для принятия/передачи значения и SwitchCase для переключения компонента и EventEmitter для сообщения изменений.

Пример на stackblitz

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>
1
  • Огромное спасибо! Всё получилось! 24 фев 2021 в 20:01

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.