Changing a component property from a directive in Angular2

I have an Angular 1 application that works with a simple directive contentEditablethat can be used in templates:

<span contenteditable="true"  ng-model="model.property" placeholder="Something">

Editing an item will trigger $setViewValue(element.html()and will work as expected.

I would like to do something in Angular2 with a similar compressed template syntax. Ideally, I would like the template to look like this:

<span contentEditable="true" [(myProperty)]="name"></span>

where 'name' is a property of the component and has the directive to update the component when changing. I feel like I'm close with this ( Plunker Link ):

//our root app component
import {Component, Input, Output Directive, ElementRef, Renderer, OnInit} from 'angular2/core'

@Directive({
    selector: '[contentEditable]',
    host: {
        '(blur)': 'update($event)'
    }
})

export class contentEditableDirective implements OnInit {
    @Input() myProperty;
    constructor(private el: ElementRef, private renderer: Renderer){}

    update(event){
      this.myProperty = this.el.nativeElement.innerText;
    }
    ngOnInit(){
        this.el.nativeElement.innerText =  this.myProperty; 
    }
}

, {name: "someName"}, , , , , , . , , , .

+4
1

name. .

@Directive({
    selector: '[contentEditable]',
    host: {
        '(input)': 'update($event)' // I changed it to input to see the changes immediatly
    }
})
export class contentEditableDirective implements OnInit {

// Output that will emit outside the directive
@Output() updateProperty: EventEmitter<any> = new EventEmitter();

// When 'update' is called we emit the value
update(event){
  this.updateProperty.emit(this.el.nativeElement.innerText);
}

, , .

<div contentEditable="true" [myProperty]="name" (updateProperty)="name = $event"></div>

updateProperty @Output. , , , , $event. $event name, .

plnkr. , .

Update

answer , , .

Output , , [()] . , [(myProperty)]="expr", [myProperty]="expr" (myPropertyChange)="expr = $event"

,

@Output() myPropertyChange: EventEmitter<any> = new EventEmitter();
update(event){
  this.myPropertyChange.emit(this.el.nativeElement.innerText);
}

, .

<div contentEditable="true" [(myProperty)]="name"></div>

plnkr .

+4

Source: https://habr.com/ru/post/1624708/


All Articles