In angular,I have a directive that takes a boolean input.
I have an anchor tag in html, where this directive is used. Now I want to set the directive's Boolean value based on the anchor tag's href value. If anchor tag's URL starts with "http:" then I want to pass yes to the Boolean value and no if otherwise.
How to achieve this in angular html component. Below is my code
**newWindow is the directive
isExternalLink is a input to the directive**
<a href="{{ object.Url}}"
newWindow Name="{{ object.Name }}" isExternalLink={{ here should apply
the condition based on the object.URL.startswith and send yes/ no }} >{{object.Name}} </a>
export class newWindow {
@Input() Name: string;
@Input() isExternalLink : string;
Use RegExp to test if the url starts with http:
Add a getter to wrap the condition
Template
<a href="{{ object.Url}}"
newWindow Name="{{ object.Name }}" [isExternalLink]={{ isExternal }} >
{{object.Name}} </a>
Component class:
export class MyComponent {
get isExternal(): boolean {
// If you want to test https too: use /^https?:/ instead
return /^http:/.test(this.object.Url)
}
// ...
}
Alternative:
If you don't want to deal with regexp, use the String method startsWith
get isExternal(): boolean {
return this.object.Url.startsWith('http:')
}
Update:
If you want to make it inline:
<a href="{{ object.Url}}"
newWindow Name="{{ object.Name }}" [isExternalLink]={{ object.Url.startsWith('http:') }} >
{{object.Name}} </a>