dag dag - 2 months ago 18
TypeScript Question

Angular2 directive - string issue

We created a directive in Angular2 and have an

input
property that should receive a
string
. The problem is that, we are not able to pass a string.

If we try to do this:

<learning-requirements [title]="You should be able to!" [content]="requirements"></learning-requirements>


It does not work, so we have to do this, and then it works:

<learning-requirements [title]="'You should be able to!'" [content]="requirements"></learning-requirements>


That is our directive:

@Component({
selector: "learning-requirements",
directives: [IONIC_DIRECTIVES],
templateUrl: "build/pages/learning/components/requirements/requirements.html"
})
export class RequirementsComponent {
@Input() public title: string;
@Input("content") public items: Array<Requirement>;
}


Any idea how to handle string whithout explicitly using single quotation?

Answer

Basically whenever you have attribute wrap with [] square bracket it is going to evaluated attribute value(expression) with context(this) of component.

Since you're directly passing a value you could directly specify title attribute without [] square bracket, which means that the value which you have passed inside attribute would not get evaluated against context(this) of component.

Markup

<learning-requirements 
  title="You should be able to!" 
  [content]="requirements">
</learning-requirements>