将 TemplateRef 推入对象

Push TemplateRef into object

目标: 将对 ng-template 的引用动态推送到一个对象中。

挑战:

  1. 我正在为每个ng-template参考手动创建@ViewChild

  2. 我不确定如何将每个 @ViewChild 推入我的 data 对象。

//Parent TS Component

export type ITabData = object[];

@Component({
    selector: 'app-style-guide',
    templateUrl: './style-guide.component.html',
    styleUrls: ['./style-guide.component.scss']
})
export class StyleGuideComponent implements OnInit {

// These are a couple <ng-templates> I'm referencing. But as some point we can have many more templates.

    @ViewChild('orderDetails') orderDetails: TemplateRef<any>;
    @ViewChild('anotherTemp') anotherTemp: TemplateRef<any>;

   // My Data object that I want to push all the ViewChild to.

    data: ITabData = [];

    constructor () {
        // I'm pretty sure this is incorrect since it did not work

        this.data.push({ tabLabel: 'newlabel', template: this.orderDetails });
    }

    ngOnInit () {

        // This is how I want the Data object be. 
       //But I want it to fill in programmatically. 
       // It displays in my view when I hardcode it inside the ngOnInit. But obvs that's not good.


        this.data = [
            {
                tabLabel: '1st Label',
                template: this.orderDetails
            },
            {
                tabLabel: '2nd Label',
                template: this.anotherTemp
            }
        ];
    }
}

我希望 Data 对象可以像这样用新对象动态填充 {tabLabel: 'My new label', template: 'my_new_template'

如果这不可能,建议将不胜感激!

谢谢大家!

你快到了。

问题是您试图在页面中创建 ViewChild 引用之前将它们推送到 constructor() 中的数组,因此 selector 不能 select还有什么。

相反,在 ngOnInit() life-cycle hook 中执行此操作,就像您手动执行的那样,这确实有效。

所以像这样:

// Illustration only, you can delete empty constructors
constructor () {}

ngOnInit() {
  this.data.push({ tabLabel: 'newlabel', template: this.orderDetails });
}

作为一般经验法则:Angular 中的 constructor() 基本上仅用于将变量初始化为已知(静态)值或注入 class 引用(如服务)。您不能在构造函数中触摸 DOM ,因为在运行时模板尚未呈现。这就是生命周期挂钩的用途。

作为 side-note:与其手动维护该对象数组,也许 @ViewChildren 会很有用。