面试题答案
一键面试1. 创建货币转换管道
在Angular项目中,首先创建一个自定义货币转换管道。
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'customEuroCurrency'
})
export class CustomEuroCurrencyPipe implements PipeTransform {
transform(value: number): string {
const euroFormatter = new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR',
minimumFractionDigits: 4,
maximumFractionDigits: 4,
currencyDisplay: 'code'
});
let formatted = euroFormatter.format(value);
// 调整货币符号位置
formatted = formatted.replace('€', '').trim() + ' €';
return formatted;
}
}
2. 在模块中声明管道
在相关的NgModule中声明这个自定义管道。假设是app.module.ts
:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform - browser';
import { AppComponent } from './app.component';
import { CustomEuroCurrencyPipe } from './custom - euro - currency.pipe';
@NgModule({
declarations: [
AppComponent,
CustomEuroCurrencyPipe
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
3. 在组件中使用管道
在组件的模板中使用这个管道来显示金额。假设app.component.ts
和app.component.html
:
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app - root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
amount: number = 1234.5678;
}
app.component.html
<div>
{{ amount | customEuroCurrency }}
</div>