ng if with angular for string contains

前端 未结 5 1004
盖世英雄少女心
盖世英雄少女心 2020-12-30 19:55

I have the following Angular code:

  • {{new.label}}
  • 5条回答
    •  悲哀的现实
      2020-12-30 20:12

      ES2015 UPDATE

      ES2015 have String#includes method that checks whether a string contains another. This can be used if the target environment supports it. The method returns true if the needle is found in haystack else returns false.

      ng-if="haystack.includes(needle)"
      

      Here, needle is the string that is to be searched in haystack.

      See Browser Compatibility table from MDN. Note that this is not supported by IE and Opera. In this case polyfill can be used.


      You can use String#indexOf to get the index of the needle in haystack.

      1. If the needle is not present in the haystack -1 is returned.
      2. If needle is present at the beginning of the haystack 0 is returned.
      3. Else the index at which needle is, is returned.

      The index can be compared with -1 to check whether needle is found in haystack.

      ng-if="haystack.indexOf(needle) > -1" 
      

      For Angular(2+)

      *ngIf="haystack.includes(needle)"
      

    提交回复
    热议问题