在Angular中,可以使用substring
方法和ngIf
指令来查看一个字符串是否在另一个字符串中。以下是一个解决方案的代码示例:
在component.ts文件中:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html'
})
export class ExampleComponent {
mainString: string = 'Hello World';
subString: string = 'World';
isSubstringPresent(): boolean {
return this.mainString.toLowerCase().includes(this.subString.toLowerCase());
}
}
在component.html文件中:
{{ subString }} is present in {{ mainString }}
{{ subString }} is not present in {{ mainString }}
在上述示例中,mainString
是要搜索的主字符串,subString
是要查找的子字符串。isSubstringPresent()
方法使用includes
方法来判断子字符串是否存在于主字符串中。根据返回的布尔值,ngIf
指令用于显示相应的结果。如果子字符串存在于主字符串中,则显示“is present”,否则显示“is not present”。
请注意,示例中的逻辑忽略了大小写,因此搜索时是不区分大小写的。如果要区分大小写,请删除toLowerCase()
方法。