【问题标题】:How to style placeholder of an element using custom directive in Angular 10?如何在 Angular 10 中使用自定义指令设置元素的占位符样式?
【发布时间】:2021-05-18 04:39:34
【问题描述】:

我有一个使用 Element Ref 和 Renderer 2 来设置元素样式的指令。我想知道如何在此指令中使用渲染器或任何其他方式设置占位符样式。

代码

TextSizeDirective.ts

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

import { Service } from '../service';

@Directive({
selector: '[textType]'
})

export class TextSizeDirective implements OnInit {

      @Input() textType: string;

      constructor(private el: ElementRef, private s:Service, private renderer: Renderer2) {}

      ngOnInit() {

      this.s.getText().subscribe(data => {

      if (data === 'max' && this.textType === 'title') {

        this.renderer.setStyle(this.el.nativeElement, 'font-size', '25px');

         //How to style placeholder of this element like above?

      }else if (data === 'max' && this.textType === 'text') {

        this.renderer.setStyle(this.el.nativeElement, 'font-size', '16px');
         //How to style placeholder of this element like above?
      } 
    });
  }
}

AppComponent.html

<div>
<h1 [textType]="'title'">Heading</h1>
<p [textType]="'text'">Paragraph</p>
<input [textType]="'text'" type="text" placeholder="Placeholder"/>
</div>

【问题讨论】:

    标签: angular-directive angular9 angular2-directives angular10 angular-renderer2


    【解决方案1】:

    您可以在要附加 ::placeholder 属性的 CSS 文件中创建一个 css 类,并在指令中使用

    import { Directive, ElementRef, Input, HostListener, Renderer2 } from '@angular/core';
    
    constructor(private el: ElementRef, private renderer: Renderer2) {
    }
    ngOnInit() {
       // for my usecase i prefere this
       this.el.nativeElement.classList.add("yourCssClass")
       // or 
       this.renderer.setElementClass(this.elementRef, 'class');
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-25
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 2019-11-29
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多