简体   繁体   English

如何在 Angular 10 中使用自定义指令设置元素的占位符?

[英]How to style placeholder of an element using custom directive in Angular 10?

I have a directive that uses Element Ref and Renderer 2 to style the element.我有一个使用 Element Ref 和 Renderer 2 来设置元素样式的指令。 I wanted to know how can I style placeholder using renderer or any other way in this directive.我想知道如何在此指令中使用渲染器或任何其他方式设置占位符的样式。

Code代码

TextSizeDirective.ts 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应用组件.html

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

you can create a css class in the CSS file where you want to append a::placeholder property and reference it in your directive with您可以在 CSS 文件中创建 css class 文件,您想在其中使用 Z9516DFB15F51C7EE19A4DBE10C 的属性并引用您的属性

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');
}

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

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