简体   繁体   English

使用Angular 6指令在组件上设置属性

[英]Use Angular 6 Directive to set property on a component

I have a custom component ComponentA with an input property Format I can use it like this: 我有一个具有输入属性Format的自定义组件ComponentA,我可以这样使用它:

<componentA Format="#.00"></componentA>

ComponentA is a 3rd party component I do not want to touch. ComponentA是我不想接触的第三方组件。

I would like to build a directive named MyFormatDirective that will set the property on that component to a fixed value of "#.00", so that instead of the above I can write: 我想构建一个名为MyFormatDirective的指令,该指令会将该组件上的属性设置为“#.00”的固定值,因此我可以编写上面的代码:

<componentA MyFormat></componentA>

This is ofcourse a simplification. 这当然是一种简化。 In reality I would like the directive to set multiple properties - basically custom configure the component 实际上,我希望该指令设置多个属性-基本上是自定义配置组件

Creating a component that wraps it is not an option, since componentA is a part of a large structure of a 3rd party library that relies on specific DOM structure. 创建包装它的组件不是一种选择,因为componentA是依赖特定DOM结构的第三方库的大型结构的一部分。 Wrapping it breaks that. 包装它打破了这一点。 Moreover, I need this approach to set multiple types of configurations by multiple directives 而且,我需要这种方法来通过多个指令设置多种类型的配置

Pls help me to acheive that, or suggest an alternative 请帮助我实现这一目标,或提出替代方案

You can just create a directive with the same selector (or a different one, but then you'll have to add an attribute to the component), and inject the component inside: 您可以使用相同的选择器(或不同的选择器)创建指令,然后必须向该组件添加一个属性,然后将该组件注入内部:

import { Directive, Input } from '@angular/core';
import { ComponentAComponent } from './component-a.component';

@Directive({
  selector: 'component-a'
})
export class ComponentADirective {
  constructor(cmp: ComponentAComponent) {
    cmp.format = '#.00';
  }
}

Complete demo: https://stackblitz.com/edit/angular-qnxqqz?file=src%2Fapp%2Fcomponent-a.directive.ts 完整的演示: https : //stackblitz.com/edit/angular-qnxqqz?file= src%2Fapp%2Fcomponent- a.directive.ts

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

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