Почему связывание свойств компонента с жестко закодированной строкой продолжает появляться неопределенным?

Если момент не работает для вас, вы можете использовать vanilla js следующим образом:

const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

// Date to convert
let myDate = "2018-04-29";
let components = myDate.split('-'); 

// 29 Apr, 2018
let newDate = components[2] + " " +monthNames[parseInt(components[1]) - 1] +", " +components[0];
console.log(newDate);

0
задан O.MeeKoh 19 January 2019 в 18:04
поделиться

2 ответа

Вы связываете значение свойства this.imageTwo, которое не существует. Таким образом, значение undefined.

Не используйте квадратные скобки, если вы хотите строковую константу

<app-my-component imgName="imageTwo"></app-my-component>
                             ^^^ = will be a string literal
0
ответ дан cgTag 19 January 2019 в 18:04
поделиться

В дополнение к ответу cgTag:

Я бы рекомендовал установить значение по умолчанию также в ngOnChanges ловушке жизненного цикла.

export class MyComponent implements OnInit, AfterViewInit {
  // moved default value to static property, to prevent duplication
  private static defaultImgName: string = "img_one";

  @Input() public imgName: string = MyComponent.defaultImgName;  

  constructor() {
    // after compiling typescript to javascript,
    // imgName property will actually be populated here
  }

  ngOnChanges(values: SimpleChanges) {
    // please note, that ngOnChanges is not executed,
    // if component is initialized w/o any bindings

    // this will be executed on every change of imgName,
    // so if you need it to be checked only once - you can do that
    // with the method values.imgName.isFirstChange()
    if (values.imgName && values.imgName.currentValue === undefined) {
       this.imgName = MyComponent.defaultImgName;
    }
  }

  ngOnInit() {
    console.log("Inside ng on init");
  }

  ngAfterViewInit() {
    console.log("imgName value is: ${this.imgName}")
  }
}
0
ответ дан yzk 19 January 2019 в 18:04
поделиться
Другие вопросы по тегам:

Похожие вопросы: