Как распечатать/показать динамическое значение в теге HTML? - программирование
Подтвердить что ты не робот

Как распечатать/показать динамическое значение в теге HTML?

Поэтому, полагая, что у меня есть компонент Angular 4, например:

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  printThisValue = 'customAttr';
  constructor(){}
}

Как напечатать значение внутри HTML-тега, как показано ниже:

<div class="myStyle" {{ printThisValue }} ></div>

HTML-код выше, похоже, не работает. Я знаю, что вы можете напечатать значение следующим образом:

<div class="myStyle">{{ printThisValue }}</div>
// or like this
<div class="myStyle {{ printThisValue }}"></div>

Но как мне это сделать?

4b9b3361

Ответ 1

Может быть лучший/более простой способ сделать это, но вы можете создать директиву, которая берет имя атрибута, а затем устанавливает его на элементе.

import { Directive, Input, ElementRef, AfterViewInit } from '@angular/core';

@Directive({ 
  selector: '[customAttr]' 
})
export class CustomDirective implements AfterViewInit {
    @Input() customAttr;
    constructor(private elRef: ElementRef) {}

    ngAfterViewInit() {
       this.elRef.nativeElement.setAttribute(this.customAttr, true);
    }       
}

Затем вы можете использовать его как: <div class="myStyle" [customAttr]="printThisValue"> и он будет испускаться с помощью <div class="myStyle" customAttr>.

Ответ 2

Проверьте, какой из них может быть вашим решением

Случай 1: Условный атрибут

<div class="myStyle" [attr.attr_name]="condition"></div>



Случай 2: имя адаптированного (динамического) имени

HTML (Шаблон)

<div #elem1>
  {{ attachAttr }} Hi
</div>

ТипScript-компонента образца

import { Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {

  myAttr = "custom_attr"; // Customize attribute name

  attachAttr: any;

  @ViewChildren('elem1') elem;

  ngAfterViewInit() {
    this.elem['first'].nativeElement.setAttribute(this.myAttr,"");
    }

}

Выход будет

<div custom_attr> Hi </div>