【问题标题】:Angular: Send element from HTMLAngular:从 HTML 发送元素
【发布时间】:2019-01-01 01:33:36
【问题描述】:

有没有办法通过 HTML 将元素作为属性发送?例如:

在 HTML 中:

<ul>
    <li *ngFor="let item of items">
         <my-component [ngClass]="{'whatever': checkElement(my-component)}">
    </li>
</ul>

在ts文件中:

checkElement(el): boolean {
     // dummy code
     const size = el.getBoundingClientRect();
     return size.bottom > 100;
}

我知道有几种方法可以获取该元素,但这将在一个巨大的循环中使用,我想防止在 DOM 中搜索该元素(如果可能的话)。

谢谢!

【问题讨论】:

    标签: html angular dom element


    【解决方案1】:

    您可以像这样引用my-component 的模板引用变量:

    <my-component [ngClass]="{'whatever': checkElement(myComponentVariableName)}" #myComponentVariableName>
    

    并将其作为参数传递给方法checkElement()。请注意,这里myComponentVariableName 的类型将是HTMLInputElement

    .ts 文件访问它的另一种方法是像这样使用@ViewChild()

    @ViewChild('myComponentVariableName') myComponentVariable: ElementRef;`.
    

    然后你可以在组件内的任何地方使用this.myComponentVariable

    如果您担心在*ngFor 中有多个my-components,您可以转换@ViewChild 语句使其成为这样的列表:

    @ViewChildren(my-component) myComponentList: QueryList<my-component>;
    

    此外,按索引跟踪*ngFor,并将索引与模板引用变量一起发送,如下所示:

    <li *ngFor="let item of items; let i=index;">
      <my-component [ngClass]="{'whatever': checkElement(myComponentVariableName, i)}" #myComponentVariableName>
    </li>
    

    checkElement() 方法中,访问特定的my-component,如myComponentList[i]

    【讨论】:

    • 这是我真正想要的。非常感谢!
    【解决方案2】:

    当然,很简单:

    export class ParentComponent {
      this = this;
    }
    
    <my-element [parentElement]="this">
    

    现在在您的第二个组件中

     @Input('parentElement') parentElement: ParentComponent;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      • 2015-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      相关资源
      最近更新 更多