ค้นหาเว็บไซต์

angular - เป็นไปได้ไหมที่จะสร้างตัวเลือก directive แบบไดนามิก (เหมือน [class.active])?


ฉันต้องการสร้างคำสั่งด้วยตัวเลือกกึ่งไดนามิก

ทีม Angular ใช้วิธีนี้ในบางที่ เช่น [style.width.px]="100" และ (keyup.enter)="doSomething()"

มีวิธีทำสิ่งนี้ในไดเร็กทีฟที่กำหนดเองของฉันไหม? บางอย่างเช่น [my-directive.some-data]="variable".

คำตอบ #1

คุณสามารถเพิ่ม @Input() ให้กับไดเรกทีฟของคุณได้ แม้ว่าการเขียนไวยากรณ์จะต่างจากที่คุณเขียนไว้เล็กน้อย

ดังนั้นคุณสามารถทำอะไรบางอย่างเช่น

<p myDirective [someData]="variable">lorem ipsum</p>

ดูเอกสารของ Angular สำหรับข้อมูลเพิ่มเติม

แก้ไข: หากคุณต้องการดูตัวอย่างที่มีหลายอินพุต ลองดูคำตอบนี้ที่นี่

คำตอบ #2

หลังจากเผยแพร่คำตอบแล้ว ผมคิดว่ามันจริง ๆ อาจจะไม่ใช่สิ่งที่คุณกำลังมองหา แต่...คุณสามารถสร้าง directive แบบนี้ได้:

@Directive({
  selector: '[mydirective.one],[mydirective.two],[mydirective.three]'
})
export class MyDirective implements OnInit {
  @Input('mydirective.one') prop1
  @Input('mydirective.two') prop2
  @Input('mydirective.three') prop3

  constructor(private el:ElementRef,private renderer:Renderer2) {}
   ngOnInit()
   {
    console.log(this.prop1,this.prop2,this.prop3)
    if (this.prop1)
       this.renderer.setStyle(this.el.nativeElement,"background-color",prop1)

    if (this.prop2)
       this.renderer.setStyle(this.el.nativeElement,"color",prop2)

    if (this.prop3)
       this.renderer.setStyle(this.el.nativeElement,"font-size",prop3)

   }
}

ดูว่าตัวเลือกสามารถแยกด้วยเครื่องหมายจุลภาคได้อย่างไร และคุณต้องใช้วิธี @Input(name.prop) variable เพราะคุณไม่สามารถใช้ตัวแปรที่แยกด้วยจุดได้

อัปเดต อาจเป็นไปได้ว่าคุณกำลังมองหาผู้โฮสต์ คุณสามารถประกาศไดเร็กทีฟแบบ

@Directive({
  selector: '[mydirective]',
  host:{'[class.active]':'value'}
})
export class MyDirective {
  value:boolean=false;
  @Input() set mydirective(value)
  {
      this.value=value;
  }