AngularJS中md-datepicker参数化md-date-locale属性渲染异常求助
Hey there! Let's break down why your aria-label isn't updating as expected and how to fix it.
The Root Cause
When you write md-date-locale="{ msgOpenCalendar: 'Open calendar for {{parameter.name}}' }" without square brackets, Angular only interpolates the string in the DOM attribute (which is why you see the correct value in the rendered md-date-locale attribute). But the md-datepicker directive is receiving a raw string instead of a parsed JavaScript object. The directive doesn't re-process this string to resolve the interpolation, so it sticks with the original {{parameter.name}} template for the aria-label.
Solution 1: Bind the Locale Object Directly
Instead of passing a string, bind the locale as a dynamic object using square brackets []. This lets Angular resolve the interpolation before passing the value to the directive, ensuring the aria-label gets the final resolved string:
<md-datepicker [md-date-locale]="{ msgOpenCalendar: 'Open calendar for ' + parameter.name }"></md-datepicker>
Solution 2: Define the Locale in Your Component (Better for Complex Scenarios)
For cleaner code—especially if you have multiple locale properties—define the locale object in your component class:
In your component's TypeScript file:
import { Component, OnInit } from '@angular/core'; @Component({ // Your component metadata here }) export class YourComponent implements OnInit { parameter = { name: 'Start Date' }; // Your existing parameter object dateLocale: any; ngOnInit(): void { this.dateLocale = { msgOpenCalendar: `Open calendar for ${this.parameter.name}` }; } }
Then in your template:
<md-datepicker [md-date-locale]="dateLocale"></md-datepicker>
Is This a Bug in md-datepicker?
Nope, this isn't a bug! The md-date-locale input is designed to accept a JavaScript object, not a string. When you pass a string (even an interpolated one), the directive can't properly parse and resolve the template variables inside it. By binding the object directly, you're giving the directive exactly what it needs to render the aria-label correctly.
内容的提问来源于stack exchange,提问作者CodeZila




