TypeScript:Object.assign数组并将数据解析到网页



我知道在typescript中使用object.assign是

Object.assign({},a,b)。目标来源然而,我正在努力了解如何将数据从文件中提取到另一个文件中。

对于一个实例,我的main.ts文件,我声明了一个数组。。

..
template:`<testing [config]="_headerConfig"></testing> `
..
private _headerConfig = { 
buttons:[
icon: "md-alarm", //this can be change depending on own preffered icon logo
type : "btn"
]
};

我创建了第二个ts.file。现在我们称之为testing.ts。该文件将与main.ts通信。父ts(main)文件将解析图标数据并键入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报警。否则它将作为_defaultConfig运行,哪个图标是默认的。

我不知道如何获取数组中的数据。我尝试使用索引指针,但它作为一个整体正在返回。

在我的html页面中,我尝试使用字符串插值来绑定第二个.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"}}]}

最新更新