【问题标题】:Angular component HTML template contains reference to itselfAngular 组件 HTML 模板包含对自身的引用
【发布时间】:2018-12-31 23:52:30
【问题描述】:

我正在查看一位同事的 Angular 代码,他在 Angular 方面比我知识渊博,努力了解更多信息。

真正让我困惑的一件事是在组件本身的 HTML 模板中使用组件的选择器。

widgetA.component.ts

import {
    Component,
    OnInit,
    Input,
    HostListener
} from '@angular/core';

// other imports here

@Component({
    selector: 'widgetA',
    templateUrl: './widgetA.component.html',
    styleUrls: ['./widgetA.component.scss']
})
export class WidgetAComponent implements OnInit {
    @Input() property1!: string;
    @Input() property2: string;

    // remainder of class here
}

widgetA.component.html

<div>
<!-- other HTML here -->
  <widgetA
    [property1]="value1" 
    [property2]="value2"
  ></widgetA>
  <widgetB
    [property3]="value3" 
    [property4]="value4"
  ></widgetB>
<!-- other HTML here -->
</div>

我不得不假设这是允许的,因为 webpack 成功编译了代码。我想我想知道这是否是典型的角度?它是一种设计模式吗?在组件本身的 HTML 模板中包含对组件的引用似乎让我感到困惑。

【问题讨论】:

    标签: angular


    【解决方案1】:

    这让我在阅读时也感到困惑,但请查看以下回复:In which way does Angular resolve duplicate directive/component selectors?

    基本上,模板中的“widgetA”是对从另一个模块导入的组件的引用。如果您尝试使用相同的组件引用本身,则应用程序将陷入递归循环并且永远无法解析。在我尝试创建的单组件堆栈闪电战中就是这种情况,它变得无响应。

    编辑:

    Stackblitz 失败演示:https://stackblitz.com/edit/angular-2zcgz8

    这是以您描述的方式递归调用组件时的控制台错误:

    基本上,在我的示例中,我有一个带有 @Component 装饰器和选择器“some”的 SomeComponent 类,如下所示:

    @Component({
      selector: 'some',
      templateUrl: './some.component.html'
    })
    export class SomeComponent {
      @Input() input1: string;
      @Input() input2: string;
    }
    

    而我的 some.component.html 包含:

    <p>{{input1}}<p>
    <p>{{input2}}</p>
    
    <some [input1]='hi'></some>
    

    【讨论】:

    • 这是我希望在我列出的代码中发生的事情,但它似乎工作正常。
    • 如果它是完全相同的组件,它不应该工作。您确定它不是来自具有相同选择器的不同模块的组件吗?
    【解决方案2】:

    选择器不是对组件的引用,它只是组件类中指定的标签名称,以便能够在我们的标记中通过使用类似的 HTML 标签来使用该组件。 混淆来自对组件类名称和选择器名称使用相同的名称“widgetA” 因此,如果您将选择器更改为另一个名称,请在 .ts 和 .html 文件中说“widA”,它仍然有效!

    【讨论】:

    • 我不同意。类名不是问题。事实上,选择器存在于组件自己的 HTML 模板中。
    猜你喜欢
    • 2017-03-12
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多