Дайте класс динамически созданной кнопке в angular - PullRequest
0 голосов
/ 08 апреля 2020

Я создаю кнопку и назначаю класс в component.ts. Стиль css не применяется к кнопке (цвет шрифта кнопки не изменяется). Код component.ts -

let button = document.createElement('button');
button.innerHTML = 'North';
button.setAttribute('class', 'btn');

let element = document.createElement('div');
element.appendChild(button);

и компонента. css -

.btn
{
  color: red;
}

Ответы [ 2 ]

0 голосов
/ 08 апреля 2020

Используйте angular компоненты для создания кнопок

@Component({
  selector: 'my-app',
  templateUrl: '',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  @ViewChild('element', { read: ViewContainerRef }) container: ViewContainerRef;

  constructor(
    private _componentFactoryResolver: ComponentFactoryResolver,
    private _injector: Injector,
  ) {}

  addButton(): void {
    const [componentRef, componentInstance] = this._createButton();
    componentInstance.title = 'North'
    componentInstance.class = 'active'

    this.container.insert(componentRef.hostView);
  }

  private _createButton(): [ComponentRef<ButtonComponent>, ButtonComponent] {
    const componentFactory = this._componentFactoryResolver.resolveComponentFactory(ButtonComponent);
    const componentRef = componentFactory.create(this._injector)

    const componentInstance = componentRef.instance;

    return [componentRef ,componentInstance];
  }
}

компонент кнопки

@Component({
  selector: 'app-button',
  templateUrl: './button.component.html',
  styleUrls: ['./button.component.css'],
})
export class ButtonComponent {
  @Input() title: string;
  @Input() class: string = '';
}

Я поместил весь пример на stackblitz

0 голосов
/ 08 апреля 2020

пожалуйста, попробуйте это

button.classList.add("btn");
...