Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

typescript - Based on condition how to set boolean value of a directive - Angular

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; 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...