Reputation: 1364
I want to assign variable's value from Component to object string within Angular view.
This is snippet from typescript file
@Input() someVariable: string = '';
let someValueFromTypeScript: string = '';
ngOnChanges(): void {
this.someValueFromTypeScript = (this.someVariable) ? this.someVariable : 'default_value';
}
This is snippet from corresponding template
<div data-dl='{"prop1":"val1", "prop2":"val2", "prop3":"someValueFromTypeScript"}'>
...
</div>
I tried using string interpolation but it didn't worked. One constraint is that value to data-dl
should be string only, so I cannot do something like:
<div attr.data-dl="JSON.stringify value of property">
...
</div>
Upvotes: 1
Views: 2193
Reputation: 31125
Since you insist on data-dl
being a string, you could use the interpolation like following
<div attr.data-dl="{prop1:val1, prop2:val2, prop3:{{someValueFromTypeScript}}}">
...
</div>
On the other hand if you wish to have an object for data-dl
attribute, you could try the property binding syntax
<div [attr.data-dl]="{'prop1':'val1', 'prop2':'val2', 'prop3':someValueFromTypeScript}">
...
</div>
Note: The type of quotation marks (single or double) doesn't have any bearing on the values. The only condition is it should be used interchangeably for member variables and string literals.
<div [attr.data-dl]="{'prop1':'val1', 'prop2':'val2', 'prop3':someValueFromTypeScript}">
is similar to
<div [attr.data-dl]='{"prop1":"val1", "prop2":"val2", "prop3":someValueFromTypeScript}'>
Upvotes: 1
Reputation: 122
Define a function into component.ts:
getSomeValueFromTypeScript(){
return this.someValueFromTypeScript;
}
And then call it from html component into your object:
<div data-dl='{"prop1":"val1", "prop2":"val2", "prop3": getSomeValueFromTypeScript() }'>
...
</div>
Upvotes: 1