angular - 包装或扩展 angular-material 组件,允许将未知属性传递给子组件
问题描述
我们正在使用 Angular 5 和材料设计,并使用各种功能的辅助方法创建我们自己的组件(即动态列生成mat-table
)。
我想要一种将未知属性从父组件传递到子组件的方法。这在 React 中很容易,例如:
应用类渲染
<MyDatatable knownVar="1" otherKnownVar="2" unknownButKnownToChildVar="3" />
MyDataTable 渲染
<MatComponent {...this.props} />
这样,如果MatComponent
更新了它所接受的属性,MyDataTable
就不必更新了。我看过@Input
装饰器,但这似乎并不能促进未知变量。
我想到的一种解决方案是只传入一个对象并通过该对象说明该对象,@Input
但我不喜欢这样,因为我希望 angular-material 组件文档能够准确地反映开发人员应该如何使用我的 MyDataTable
组件。
我的问题的简短版本:如何将下落不明的属性级数据传递给 Angular 5 中的子组件?
解决方案
我可以想到使用 Angular 提供的 Input 装饰器做你想做的事情的一种方法是将JS 对象(任意)传递到组件输入中,并根据属性执行所需的代码。例子:
我的组件.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
@Input() data: any;
constructor() { }
ngOnInit() { }
}
app.component.html
<my-component [data]="{data: 2, extraData: 3}"></my-component>
在这种情况下,您可以在输入数据中添加n* 个属性。没有将未知数量的属性传递给组件的任何实现。
您还可以做的另一件很酷的事情是在您的组件内部,您实际上可以有一些默认值,并且还可以期待更多。就像这里的例子:
app.component.html
<my-component [data]="{name: 'John', surname: 'Doe'}"></my-component>
我的组件.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
@Input() data: any;
constructor() { }
ngOnInit() {
this.data = {
name: "John",
surname: "Doe",
origin: "UK",
...this.data
}
}
}
我的组件.component.html
<div *ngIf="data.phone">
Phone Number: {{ data.phone }}
</div>
或者甚至制作某种Object.keys(this.data)并遍历数据属性并打印正确的 html。这样,您可以为已知属性设置一些默认值,甚至可以期待更多未知属性。
希望我有任何帮助。
推荐阅读
- python - 我的暂停显示如何在 Pygame 中正常工作?
- php - 为什么即使类确实存在并且命名空间正确,我也会收到错误 Class not found
- forms - 使用多个按钮时 SwiftUI 表单容器中的意外行为
- html - 使用视频标签嵌入 Html5 时视频放大
- pandas - Tkinter Scale 以将值输入到 pandas dataframe.head
- firewall - pfSense - 子网之间的防火墙
- reactjs - 用是的缺少属性反应正式打字稿
- android - 更改 React Native 的节点模块后如何重建项目
- node.js - “未找到 webpack binstubs。” 在 Heroku 上
- c# - HttpClient ReadAsStringAsync 与进度