angular 7如何通过子组件模板中父组件中定义的id访问元素

问题描述 投票:0回答:2

我在子组件中使用了primeng multiSelect控件。我希望将其附加到父组件中定义的元素,如上所示。当我运行npm run build:prod时,上面的代码失败了。它无法访问子进程中的popupContent。任何人都可以帮助如何访问子组件中的父元素?

**Parent component:**

                <tbody app-sg-add-edit-subline-agg (sublineSave)="onSublineSave($event)" #popupContent>   
                </tbody>

**sg-add-edit-subline-agg component:**
                <p-multiSelect optionLabel="name"
                   [options]="sublines"
                   formControlName="name"
                   [appendTo]="popupContent">   

谢谢

angular7 primeng
2个回答
0
投票

任何人都可以帮助如何访问子组件中的父元素?

The Example shown below is from the Angular Documents

父母需要使用@Input()功能发送数据。但是,还有其他方法可以将信息从Child传递给Parent,Parent传递给Child,就像使用service一样。这只是一个基本的例子。

父组件从'@ angular / core'导入{Component};

import { HEROES } from './hero';
    @Component({
      selector: 'app-hero-parent',
      template: `
        <h2>{{master}} controls {{heroes.length}} heroes</h2>
        <app-hero-child *ngFor="let hero of heroes"
          [hero]="hero"
          [master]="master">
        </app-hero-child>
      `
    })
    export class HeroParentComponent {
      heroes = HEROES;
      master = 'Master';
    }

子组件

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

import { Hero } from './hero';

@Component({
  selector: 'app-hero-child',
  template: `
    <h3>{{hero.name}} says:</h3>
    <p>I, {{hero.name}}, am at your service, {{masterName}}.</p>
  `
})
export class HeroChildComponent {
  @Input() hero: Hero;
  @Input('master') masterName: string;
}

0
投票

说明:

我们使用引用模板变量来使用#popupComponent获取父引用。然后我们将它作为@Input()属性传递给子节点。

父组件:

<tbody app-sg-add-edit-subline-agg 
       (sublineSave)="onSublineSave($event)" 
       #popupContent [popupContent]="popupContent">   
</tbody>

SG-添加 - 编辑 - 亚系,agg.component.html:

<p-multiSelect optionLabel="name"
[options]="sublines"
formControlName="name"
[appendTo]="popupContent">   

确保在sg-add-edit-subline-agg.component.ts中添加@Input属性

@Input() popupContent;

StackBlitz有一个更简单的上述概念的例子:https://stackblitz.com/edit/primeng-parent-child?file=app%2Fapp.component.html

© www.soinside.com 2019 - 2024. All rights reserved.