angular - 如何使用角度从html中的数组中提取前两个字符?
问题描述
我有一个 api 数组对象返回值如下:
apival = [{lang: "English",code: "en-ca"}, {lang: "French",code: "fr-ca"}]
我将这个数组与 ngfor 一起使用来显示 html 中的语言。我需要指定一个条件来应用一些逻辑。为此,我需要一个管道或其他东西,它可以在运行时从代码中提取前两个字符。
我知道如何在打字稿中拆分它。但是,我需要它在 HTML 中。在我的 TS 中:
currentlang = "en"
在我的 HTML 中:
<div*ngfor="let x of apival">
<div*ngIf="x.code == currentlang"></div>
</div>
在上面的 html 代码中,我需要一种从代码中提取前两个字符的方法。知道我该怎么做吗?
我不想使用 TS,我可以在 html 中使用管道或一些逻辑
解决方案
是的,使用Pipe
它是正确的方法。尝试这个:
@Pipe({ name: "code" })
export class LangCodePipe implements PipeTransform {
transform(value: any[], filter?: string): any {
return value
.map(lang => {
return {
...lang,
short: lang.code.split("-")[0]
};
})
.filter(lang => {
return filter ? filter == lang.short : true;
});
}
}
它将包含您需要的逻辑,并使过滤器成为可选的,Pipe
返回实际对象以及短代码。
现在您需要做的就是:在模块中声明管道并在模板中使用它。
<!--currentLang is optional param-->
<div *ngFor="let x of apival | code: currentlang">
{{x | json}}
</div>
<!-- you can also do this -->
<div *ngFor="let x of apival | code">
{{x | json}}
</div>
推荐阅读
- excel-formula - 在 Excel 单元格引用中使用日期
- excel - 使用VBA根据excel单元格内容更改字体类型
- python-3.x - 如何将熊猫数据框保存到文件位置,然后将该文件添加到电子邮件附件
- html - 您如何禁用删除 atom-beautify 中的多个空格?
- python - How to perform operation over each dictionary in column?
- msys2 - How to make the shell start at a specific folder with MSYS2?
- typescript - MSGraph - 是否可以对从 API 调用的属性进行切片?
- homebrew - Homebrew list packages I have installed
- java - How to import a module to a class in intelliJ?
- reactjs - Error in website deployed in VM with Nginx