简体   繁体   English

Angular 14 - 从 dom 中删除子组件标签

[英]Angular 14 - Remove child component tag from dom

Using Angular 14使用Angular 14

I have the following button component我有以下button组件

button.component.html按钮.component.html

<button class="btn btn-{{color}} my-4 mb-2"
        [class.btn-sm]="size === 'sm'"
        (click)="onClick.emit()">
  <ng-content select="[label]"></ng-content>
</button>

and button.component.tsbutton.component.ts

@Component({
  selector: 'app-button',
  templateUrl: './button.component.html',
  styleUrls: ['./button.component.scss']
})
export class ButtonComponent {

  @Input() color: 'primary'|'secondary'|'success' = 'primary';

  @Input() size: 'default'|'sm'|'lg' = 'default';

  @Output() onClick: EventEmitter<any> = new EventEmitter<any>();

  constructor() { }
}

Now I want to group the ButtonComponent to create button group as per the bootstrap 5, which should be like现在我想根据 bootstrap 5 对ButtonComponent进行分组以创建按钮组,这应该类似于

<div class="btn-group" role="group">
  <button class="btn btn-primary">Button 1</button>
  <button class="btn btn-primary">Button 2</button>
</div>

But with the above html component, doing it like但是使用上面的 html 组件,就像

<div class="btn-group" role="group">
  <app-button [color]="'primary'">
    <ng-container label>Button 1</ng-container>
  </app-button>
  <app-button [color]="'danger'">
    <ng-container label>Button 2</ng-container>
  </app-button>
</div>

which is generating dom like正在生成 dom 之类的

<div class="btn-group" role="group">
  <app-button>
    <button class="btn btn-primary">Button 1</button>
  </app-button>
  <app-button>
    <button class="btn btn-primary">Button 2</button>
  </app-button>
</div>

This is resulting in breaking UI as the next child of btn-group should be button and not ng-button .这会导致 UI 中断,因为btn-group的下一个子元素应该是button而不是ng-button

How can I remove extra <app-button> from the dom?如何从 dom 中删除多余的<app-button>

Angular will always render the component in the dom (if it has a selector). Angular 将始终在 dom 中呈现组件(如果它有选择器)。 What you want is a directive .你想要的是一个directive

@Directive({
  selector: '[myButton]',
})
export class HelloDirective implements OnChanges {
  @Input() name: string;

  @Input() color: 'primary' | 'secondary' | 'success' = 'primary';
  @Input() size: 'default' | 'sm' | 'lg' = 'default';
  @Input() class: string = '';

  @HostBinding('class')
  customClass = `btn my-4 mb-2 btn-${this.color} btn-${this.size} ${this.class}`;

  ngAfterViewInit() {
    console.log(this);
  }

  ngOnChanges() {
    this.customClass = `btn my-4 mb-2 btn-${this.color} btn-${this.size} ${this.class}`;
  }
}

Usage:用法:

<button myButton color="secondary" size="lg" class="btn btn-primary">
   Button
</button>

which renders:呈现:

<button  class="test btn btn-lg btn-secondary mb-2 my-4">
   Button
</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM