1

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>

2 Answers 2

1

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}'>
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.