我知道在打字稿中使用 object.assign 是
Object.assign({},a , b) . target...source.
但是,我试图了解如何将数据从文件获取到另一个文件。
举个例子,在我的
main.ts
文件中,我声明了一个数组:
..
template:`<testing [config]="_headerConfig"></testing> `
..
private _headerConfig = {
buttons:[
icon: "md-alarm", // this can be change depending on own preferred icon logo
type : "btn"
]
};
我创建了第二个
.ts
文件,我们现在称之为 testing.ts
。该文件将与 main.ts
进行通信。父 ts(主)文件将解析图标数据并输入 testing.ts
。
..
..
@Component
selector: "testing";
..
..
..
// I am not sure if I do need to declare this as empty array object.
// First I declared an an empty array
public button_message : any =[{}];
// Setting default values
private _defaultConfig: any = {
leftButton : [{icon : "Default",
path : "Default"}
],
};
// This is where I used object.assign I want
let config = this.config.leftButton;
console.log ("object 1 is developer input" , config); //this will display the inputs from main.ts
let defaultConfig = this._defaultConfig.leftButton; //this will display the input from the _defaultConfig
console.log ("object2 is default input", defaultConfig)
let finalConfig = Object.assign({}, config, defaultConfig);
console.log("This is Object Assing log" , finalConfig)
我尝试了无数的方法来计算这部分。
如果
testing.ts
内有输入图标,则会显示为md-alarm
。
否则它将作为默认图标
_defaultConfig
运行。
我不确定如何获取数组内的数据。我尝试使用索引指针,但它作为一个整体返回。
在我的 html 页面中,我尝试使用字符串插值来绑定 secondary.ts 文件中的数据。但我总是收到错误。
举个例子:我想将开发者的数据输入图标绑定到
md-alarm
,例如,这是我的second.html
,它链接到second.ts
:
<button class="logo-btn">
<name="{{button_message.icon}}">
</>
</button>
未解析任何消息。
任何帮助将不胜感激。
让我们看看我的理解是否正确。我会分配父组件中已有的默认值,例如:'
private _headerConfig = {
buttons: [
{
leftButton: {
icon: "md-1-default"
type: "btn"
},
},
{
rightButton: {
icon: "md-2-default"
type: "btn"
},
},
]
};
然后你就有了这个,它将你的
_headerConfig
传递给孩子
<testing [config]="_headerConfig"></testing>
在您的子组件中,您需要以下内容:
@Input() config;
你捕获了
OnInit
中的值:
ngOnInit() {
console.log(JSON.stringify(this.config));
}
将输出:
{"buttons":[{"leftButton":{"icon":"md-2-default","type":"btn"}},{"rightButton":{"icon":"md-2-default","type":"btn"}}]}
显然您想要接受用户输入并更改这些默认值。为此,您可以使用例如
(ngModelChange)="updateValue(your parameter)"
实际上不知道你是如何做到这一点的,我只是手动为 leftButton 分配一个新的自定义值:
this._headerConfig.buttons[0] = { leftButton: { icon: 'custom', type: 'custom' } }
然后你就可以用这些值做你想做的事了。如果您愿意,您可以在子视图中关注更改:
<div>{{config | json}}</div>
因此,上述更改将 JSON 字符串化,然后如下所示:
{"buttons":[{"leftButton":{"icon":"custom","type":"custom"}},{"rightButton":{"icon":"md-1-default","type":"btn"}}]}