【问题标题】:Angular change html tag programmatically when inheriting template继承模板时以编程方式更改 html 标记
【发布时间】:2021-08-04 09:26:18
【问题描述】:

我有一个组件 DataGrid,它表示一个带有可扩展行的表。每一行在展开时都会显示一个子 DataGrid 表,该表与父 DataGrid 组件非常相似。 因此我定义了一个基类DataGridComponent,子类继承了组件和模板。但是,我需要更改孩子模板中的其中一个标签。我是否必须重写整个模板,或者我可以将 templateUrl 指向父模板并以编程方式更改我需要更改的一个 html 标记?

小例子:

base.component.ts

@Component({
 selector: 'datagrid',
 templateUrl: 'datagrid.component.html'
})
export class DataGridComponent {
    childEnabled:boolean = true;
 // stuff
}

datagrid.component.html

<div>...</div>
<div *ngIf="childEnabled">
    <childgrid
     [options]="childOptions"
     >
    </childgrid>
</div>

child.component.ts

@Component({
 selector: 'childgrid',
 templateUrl: 'datagrid.component.html' // <-- POINT TO BASECLASS TEMPLATE
})
export class ChildGridComponent extends DataGridComponent{
}

childgrid.component.html //

<div>...</div>
<div *ngIf="childEnabled">
    <grandchildgrid
     [options]="childOptions"
     >
    </grandchildgrid>
</div>

grandchild.component.ts

@Component({
 selector: 'grandchildgrid',
 templateUrl: 'datagrid.component.html' // <-- POINT TO BASECLASS TEMPLATE
})
export class GrandChildGridComponent extends DataGridComponent{
 constructor() {
  super();
  childEnable=false;
 }
}

grandchildgrid.component.html //

<div>...</div>
<div *ngIf="childEnabled">
    <grandchildgrid
     [options]="childOptions"
     >
    </grandchildgrid>
</div>

以此类推,直到 childEnabled 设置为 false。有没有机会做这样的事情,从角度来看这是否有意义? ng-content 在这种情况下会有帮助吗?

【问题讨论】:

  • 我认为您可以将 @Input 传递给您的 DataGridComponent 并且 *ngIf 可以成功。另一种选择是,在构造函数中,使用 constructor(@Optional() @SkipSelf() private parent:DataGridComponent) 之类的函数并检查 parent 是否为 null - 请参阅文档中的 skipSelf:angular.io/api/core/SkipSelf-。注意:顺便说一句,在 Angular 中允许使用递归组件,也许这就是你要找的
  • 谢谢,我去看看SkipSelf。我的组件并不完全是递归的,因为每个子组件都派生自一个基础组件,所以每个嵌套组件都与其父组件有点不同

标签: html angular templates inheritance tags


【解决方案1】:
  • DataGrid 的内容可以进入单独的组件,并且可以在父 DataGrid 和子 DataGrid 中用作模板。
  • 替代选项是使用不同的类和 id 为父级和子级使用相同的标签和控制行为

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 2012-08-17
    • 2018-11-11
    相关资源
    最近更新 更多