【问题标题】:Angular component selector on a bound attribute value绑定属性值上的 Angular 组件选择器
【发布时间】:2021-07-21 16:11:45
【问题描述】:

我正在尝试在属性值上编写组件选择器,如下所示:

selector: '[data-type=Type1]'

这在以下 HTML 中效果很好:

<div *ngFor="let item of items">
  <div data-type="Type1"></div>
</div>

但不能这样工作(这当然是我想要的):

<div *ngFor="let item of items">
  <div [data-type]="item.type"></div>
</div>

我猜这是由于 Angular 解决问题的顺序。我想要的可能吗?

【问题讨论】:

    标签: angular components selector


    【解决方案1】:

    不能根据更改检测添加或删除指令。指令要么一直存在,要么不存在。

    您的指令应将data-type 值作为输入,然后确定是否执行其工作。

    例如

    @Directive({
      selector: '[data-type]'
    })
    export class DataTypeDirective {
      @Input('data-type') dataType: string;
    
      doSomeStuff() {
        if (this.dataType !== 'Type1') {
          return;
        }
        // perform the directive's function
      }
    }
    

    或者如果它是一个组件,在模板中使用*ngIf:

    <div *ngIf="dataType === 'Type1'">
      <!-- the component's body -->
    </div>
    

    【讨论】:

    • 它是一个组件,我希望能够拥有很多组件,在需要时添加更多组件,而不必随着 ngIf 数量的增加而更新使用它们的所有 HTML。我在你的回答中读到的就是我发布问题时的情况:不可能。
    • 不用更新使用的模板,只需要更新组件本身的模板,一次就可以了。
    • 我明白你在说什么。这还不错。
    【解决方案2】:

    我认为语法可能存在小问题。尝试使用“[selector_name]”。添加链接,this one 供选择器使用。

    【讨论】:

    • 我不关注你。您认为具体需要改变什么?
    • 在选择器中 -> 选择器:'[selector_value]' 在组件中 -> @Component({ 选择器:'[my-app]', templateUrl: './app.component.html', styleUrls : [ './app.component.css' ] }) 在 HTML ->
    • 所以上面那个是把选择器作为属性的正确格式。你已经做到了!
    【解决方案3】:

    对于属性绑定语法类似于属性绑定,但不是括号之间的元素属性,而是在属性名称之前加上前缀 attr,后跟一个点。然后,使用解析为字符串的表达式设置属性值。 https://angular.io/guide/attribute-binding

    在你的情况下,应该是这样的

    <div *ngFor="let item of items">
      <div [attr.data-type]="item.type"></div>
    </div>
    

    【讨论】:

    • 恐怕这似乎也不起作用。没有让组件与 div 匹配。
    • 应该工作,对我来说在这里工作stackblitz.com/edit/…
    • 在您的堆栈闪电战中,我看不到您在哪里为任何组件指示了基于属性值的选择器。请查看我的问题中的第一个代码块。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 2017-03-16
    • 2020-03-22
    • 2017-11-29
    • 2016-05-11
    • 2018-08-14
    相关资源
    最近更新 更多