I am writing an Angular application and I have an HTML response I want to display.
How do I do that? If I simply use the binding syntax {{myVal}} it encodes all HTML characters (of course).
I need somehow to bind the innerHTML of a div to the variable value.
The correct syntax is the following:
<div [innerHTML]="theHtmlString"></div>
Documentation Reference
Angular 2.0.0 and Angular 4.0.0 final
For safe content just
<div [innerHTML]="myVal"></div>
DOMSanitizer
Potential unsafe HTML needs to be explicitly marked as trusted using Angulars DOM sanitizer so doesn't strip potentially unsafe parts of the content
<div [innerHTML]="myVal | safeHtml"></div>
with a pipe like
#Pipe({name: 'safeHtml'})
export class Safe {
constructor(private sanitizer:DomSanitizer){}
transform(style) {
return this.sanitizer.bypassSecurityTrustHtml(style);
//return this.sanitizer.bypassSecurityTrustStyle(style);
// return this.sanitizer.bypassSecurityTrustXxx(style); - see docs
}
}
See also In RC.1 some styles can't be added using binding syntax
And docs: https://angular.io/api/platform-browser/DomSanitizer
Security warning
Trusting user added HTML may pose a security risk. The before mentioned docs state:
Calling any of the bypassSecurityTrust... APIs disables Angular's built-in sanitization for the value passed in. Carefully check and audit all values and code paths going into this call. Make sure any user data is appropriately escaped for this security context. For more detail, see the Security Guide.
Angular markup
Something like
class FooComponent {
bar = 'bar';
foo = `<div>{{bar}}</div>
<my-comp></my-comp>
<input [(ngModel)]="bar">`;
with
<div [innerHTML]="foo"></div>
won't cause Angular to process anything Angular-specific in foo.
Angular replaces Angular specific markup at build time with generated code. Markup added at runtime won't be processed by Angular.
To add HTML that contains Angular-specific markup (property or value binding, components, directives, pipes, ...) it is required to add the dynamic module and compile components at runtime.
This answer provides more details How can I use/create dynamic template to compile dynamic Component with Angular 2.0?
[innerHtml] is great option in most cases, but it fails with really large strings or when you need hard-coded styling in html.
I would like to share other approach:
All you need to do, is to create a div in your html file and give it some id:
<div #dataContainer></div>
Then, in your Angular 2 component, create reference to this object (TypeScript here):
import { Component, ViewChild, ElementRef } from '#angular/core';
#Component({
templateUrl: "some html file"
})
export class MainPageComponent {
#ViewChild('dataContainer') dataContainer: ElementRef;
loadData(data) {
this.dataContainer.nativeElement.innerHTML = data;
}
}
Then simply use loadData function to append some text to html element.
It's just a way that you would do it using native javascript, but in Angular environment. I don't recommend it, because makes code more messy, but sometimes there is no other option.
See also Angular 2 - innerHTML styling
On angular2#2.0.0-alpha.44:
Html-Binding will not work when using an {{interpolation}}, use an "Expression" instead:
invalid
<p [innerHTML]="{{item.anleser}}"></p>
-> throws an error (Interpolation instead of expected Expression)
correct
<p [innerHTML]="item.anleser"></p>
-> this is the correct way.
you may add additional elements to the expression, like:
<p [innerHTML]="'<b>'+item.anleser+'</b>'"></p>
hint
HTML added using [innerHTML] (or added dynamically by other means like element.appenChild() or similar) won't be processed by Angular in any way except sanitization for security purposed.
Such things work only when the HTML is added statically to a components template. If you need this, you can create a component at runtime like explained in How can I use/create dynamic template to compile dynamic Component with Angular 2.0?
Using [innerHTML] directly without using Angular's DOM sanitizer is not an option if it contains user-created content. The safeHtml pipe suggested by #GünterZöchbauer in his answer is one way of sanitizing the content. The following directive is another one:
import { Directive, ElementRef, Input, OnChanges, Sanitizer, SecurityContext,
SimpleChanges } from '#angular/core';
// Sets the element's innerHTML to a sanitized version of [safeHtml]
#Directive({ selector: '[safeHtml]' })
export class HtmlDirective implements OnChanges {
#Input() safeHtml: string;
constructor(private elementRef: ElementRef, private sanitizer: Sanitizer) {}
ngOnChanges(changes: SimpleChanges): any {
if ('safeHtml' in changes) {
this.elementRef.nativeElement.innerHTML =
this.sanitizer.sanitize(SecurityContext.HTML, this.safeHtml);
}
}
}
To be used
<div [safeHtml]="myVal"></div>
Please refer to other answers that are more up-to-date.
This works for me: <div innerHTML = "{{ myVal }}"></div> (Angular2, Alpha 33)
According to another SO: Inserting HTML from server into DOM with angular2 (general DOM manipulation in Angular2), "inner-html" is equivalent to "ng-bind-html" in Angular 1.X
Just to make for a complete answer, if your HTML content is in a component variable, you could also use:
<div [innerHTML]=componentVariableThatHasTheHtml></div>
Short answer was provided here already: use <div [innerHTML]="yourHtml"> binding.
However the rest of the advices mentioned here might be misleading. Angular has a built-in sanitizing mechanism when you bind to properties like that. Since Angular is not a dedicated sanitizing library, it is overzealous towards suspicious content to not take any risks. For example, it sanitizes all SVG content into empty string.
You might hear advices to "sanitize" your content by using DomSanitizer to mark content as safe with bypassSecurityTrustXXX methods. There are also suggestions to use pipe to do that and that pipe is often called safeHtml.
All of this is misleading because it actually bypasses sanitizing, not sanitizing your content. This could be a security concern because if you ever do this on user provided content or on anything that you are not sure about — you open yourself up for a malicious code attacks.
If Angular removes something that you need by its built-in sanitization — what you can do instead of disabling it is delegate actual sanitization to a dedicated library that is good at that task. For example — DOMPurify.
I've made a wrapper library for it so it could be easily used with Angular:
https://github.com/TinkoffCreditSystems/ng-dompurify
It also has a pipe to declaratively sanitize HTML:
<div [innerHtml]="value | dompurify"></div>
The difference to pipes suggested here is that it actually does do the sanitization through DOMPurify and therefore work for SVG.
EDIT: Angular no longer sanitizes CSS as of Ivy renderer so below info, kept for history sake, is irrelevant:
One thing to keep in mind is DOMPurify is great for sanitizing HTML/SVG, but not CSS. So you can provider Angular's CSS sanitizer to handle CSS:
import {NgModule, ɵ_sanitizeStyle} from '#angular/core';
import {SANITIZE_STYLE} from '#tinkoff/ng-dompurify';
#NgModule({
// ...
providers: [
{
provide: SANITIZE_STYLE,
useValue: ɵ_sanitizeStyle,
},
],
// ...
})
export class AppModule {}
It's internal — hence ɵ prefix, but this is how Angular team use it across their own packages as well anyway. That library also works for Angular Universal and server side rendering environment.
I apologize if I am missing the point here, but I would like to recommend a different approach:
I think it's better to return raw data from your server side application and bind it to a template on the client side. This makes for more nimble requests since you're only returning json from your server.
To me it doesn't seem like it makes sense to use Angular if all you're doing is fetching html from the server and injecting it "as is" into the DOM.
I know Angular 1.x has an html binding, but I have not seen a counterpart in Angular 2.0 yet. They might add it later though. Anyway, I would still consider a data api for your Angular 2.0 app.
I have a few samples here with some simple data binding if you are interested: http://www.syntaxsuccess.com/viewarticle/angular-2.0-examples
Just simply use [innerHTML] attribute in your HTML, something like this below:
<div [innerHTML]="myVal"></div>
Ever had properties in your component that contain some html markup or
entities that you need to display in your template? The traditional
interpolation won't work, but the innerHTML property binding comes to
the rescue.
Using {{myVal}} Does NOT work as expected! This won't pick up the HTML tags like <p>, <strong> etc and pass it only as strings...
Imagine you have this code in your component:
const myVal:string ='<strong>Stackoverflow</strong> is <em>helpful!</em>'
If you use {{myVal}}, you will get this in the view:
<strong>Stackoverflow</strong> is <em>helpful!</em>
but using [innerHTML]="myVal"makes the result as expected like this:
Stackoverflow is helpful!
<div [innerHTML]="HtmlPrint"></div><br>
The innerHtml is a property of HTML-Elements, which allows you to set it’s html-content programatically. There is also a innerText property which defines the content as plain text.
The [attributeName]="value" box bracket , surrounding the attribute defines an Angular input-binding. That means, that the value of the property (in your case innerHtml) is bound to the given expression, when the expression-result changes, the property value changes too.
So basically [innerHtml] allows you to bind and dynamically change the html-conent of the given HTML-Element.
You can apply multiple pipe for style, link and HTML as following in .html
<div [innerHTML]="announcementContent | safeUrl| safeHtml">
</div>
and in .ts pipe for 'URL' sanitizer
import { Component, Pipe, PipeTransform } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
#Pipe({ name: 'safeUrl' })
export class SafeUrlPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
pipe for 'HTML' sanitizer
import { Component, Pipe, PipeTransform } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
#Pipe({
name: 'safeHtml'
})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}
transform(value) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
this will apply both without disturbing any style and link click event
In Angular 2 you can do 3 types of bindings:
[property]="expression" -> Any html property can link to an
expression. In this case, if expression changes property will update,
but this doesn't work the other way.
(event)="expression" -> When event activates execute expression.
[(ngModel)]="property" -> Binds the property from js (or ts) to html. Any update on this property will be noticeable everywhere.
An expression can be a value, an attribute or a method. For example: '4', 'controller.var', 'getValue()'
Example here
We can always pass html content to innerHTML property to render html dynamic content but that dynamic html content can be infected or malicious also. So before passing dynamic content to innerHTML we should always make sure the content is sanitized (using DOMSanitizer) so that we can escaped all malicious content.
Try below pipe:
import { Pipe, PipeTransform } from "#angular/core";
import { DomSanitizer } from "#angular/platform-browser";
#Pipe({name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {
}
transform(value: string) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
Usage:
<div [innerHTML]="content | safeHtml"></div>
You can also bind the angular component class properties with template using DOM property binding.
Example: <div [innerHTML]="theHtmlString"></div>
Using canonical form like below:
<div bind-innerHTML="theHtmlString"></div>
Angular Documentation: https://angular.io/guide/template-syntax#property-binding-property
See working stackblitz example here
You can use the Following two ways.
<div [innerHTML]="myVal"></div>
or
<div innerHTML="{{myVal}}"></div>
Angular 2+ supports an [innerHTML] property binding that will render HTML. If you were to otherwise use interpolation, it would be treated as a string.
Into .html file
<div [innerHTML]="theHtmlString"></div>
Into .ts file
theHtmlString:String = "enter your html codes here";
I have build below library which will help to rebind html formatted bindings.
Please find below steps to use this library. This library basically allows to inject JIT compilter code in AOT
Install library using
npm i angular-html-recompile
Add below code in app.component.html file
<pk-angular-html-recompile *ngIf="template !== ''"
[stringTemplate]="template"
[data]="dataObject">
</pk-angular-html-recompile>
Use below code in app.component.ts file
import { Component, OnInit, ViewChild } from '#angular/core';
import { AngularHtmlRecompileComponent, AngularHtmlRecompileService } from 'angular-html-recompile';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
#ViewChild(AngularHtmlRecompileComponent, { static: true }) comp !: AngularHtmlRecompileComponent;
constructor(
private angularHtmlRecompileService: AngularHtmlRecompileService) {
}
public dataObject: any;
public template = `<div class="login-wrapper" fxLayout="row" fxLayoutAlign="center center">
<mat-card class="box">
<mat-card-header>
<mat-card-title>Register</mat-card-title>
</mat-card-header>
<form class="example-form">
<mat-card-content>
<mat-form-field class="example-full-width">
<input matInput placeholder="Username" [value]="Username" (keydown)="onControlEvent($event,'Username')">
</mat-form-field>
<mat-form-field class="example-full-width">
<input matInput placeholder="Email" [value]="Email" (keydown)="onControlEvent($event,'Email')">
</mat-form-field>
<mat-form-field *ngIf="isShow" class="example-full-width">
<input matInput placeholder="Password" [value]="Password" (keydown)="onControlEvent($event,'Password')">
</mat-form-field>
<mat-form-field class="example-full-width">
<mat-label>Choose a role...</mat-label>
<mat-select (selectionChange)="onControlEvent($event, 'selectedValue')">
<mat-option [value]="roles" *ngFor="let roles of Roles">{{roles}}
</mat-option>
</mat-select>
</mat-form-field>
</mat-card-content>
<button mat-stroked-button color="accent" class="btn-block" (click)="buttomClickEvent('submit')" >Register</button>
</form>
</mat-card>
</div>`;
ngOnInit(): void {
this.angularHtmlRecompileService.sharedData.subscribe((respose: any) => {
if (respose) {
switch (respose.key) {
case `Username`:
// Call any method on change of name
break;
case `Password`:
//Update password from main component
this.comp[`cmpRef`].instance['Password'] = "Karthik";
break;
case `submit`:
//Get reference of all parameters on submit click
//1. respose.data OR
//use this.comp[`cmpRef`].instance
break;
default:
break;
}
}
});
this.prepareData();
}
prepareData() {
//Prepare data in following format only for easy binding
//Template preparation and data preparation can be done once data received from service
// AngularHtmlRecompileComponent will not be rendered until you pass data
this.dataObject = [
{ key: 'Username', value: 'Pranay' },
{ key: 'Email', value: 'abc#test.com', },
{ key: 'Password', value: 'test123', },
{ key: 'Roles', value: ['Admin', 'Author', 'Reader'] },
{ key: 'isShow', value: this.updateView() }
];
}
updateView() {
//Write down logic before rendering to UI to work ngIf directive
return true;
}
}
Add module into app.module.ts file
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import { AngularHtmlRecompileModule } from "angular-html-recompile";
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AngularHtmlRecompileModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
This library supports basic html, Angular material, flex layouts.
To use this features install below dependencies
npm i -s #angular/material #angular/flex-layout
The way to dynamically add elements to DOM, as explained on Angular 2 doc, is by using ViewContainerRef class from #Angular/core.
What you have to do is to declare a directive that will implement ViewContainerRef and act like a placeholder on your DOM.
Directive
import { Directive, ViewContainerRef } from '#angular/core';
#Directive({
selector: '[appInject]'
})
export class InjectDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
Then, in the template where you want to inject the component:
HTML
<div class="where_you_want_to_inject">
<ng-template appInject></ng-template>
</div>
Then, from the injected component code, you will inject the component containing the HTML you want:
import { Component, OnInit, ViewChild, ComponentFactoryResolver } from '#angular/core';
import { InjectDirective } from '../inject.directive';
import { InjectedComponent } from '../injected/injected.component';
#Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
#ViewChild(InjectDirective) injectComp: InjectDirective;
constructor(private _componentFactoryResolver: ComponentFactoryResolver) {
}
ngOnInit() {
}
public addComp() {
const componentFactory = this._componentFactoryResolver.resolveComponentFactory(InjectedComponent);
const viewContainerRef = this.injectComp.viewContainerRef;
const componentRef = viewContainerRef.createComponent(componentFactory);
}
public removeComp() {
const componentFactory = this._componentFactoryResolver.resolveComponentFactory(InjectedComponent);
const viewContainerRef = this.injectComp.viewContainerRef;
const componentRef = viewContainerRef.remove();
}
}
I added a fully working demo app on Angular 2 dynamically add component to DOM demo
You can use several approaches to achieve the solution. As already said in the approved answer, you can use:
<div [innerHTML]="myVal"></div>
depending on what you are trying to achieve, you can also try other things like javascript DOM (not recommended, DOM operations are slow):
Presentation
<div id="test"></test>
Component
var p = document.getElementsById("test");
p.outerHTML = myVal;
Property Binding
Javascript DOM Outer HTML
If you want that in Angular 2 or Angular 4 and also want to keep inline CSS then you can use
<div [innerHTML]="theHtmlString | keepHtml"></div>
Working in Angular v2.1.1
<div [innerHTML]="variable or htmlString">
</div>
Just to post a little addition to all the great answers so far: If you are using [innerHTML] to render Angular components and are bummed about it not working like me, have a look at the ngx-dynamic-hooks library that I wrote to address this very issue.
With it, you can load components from dynamic strings/html without compromising security. It actually uses Angular's DOMSanitizer just like [innerHTML] does as well, but retains the ability to load components (in a safe manner).
See it in action in this Stackblitz.
If you have templates in your angular (or whatever framework) application, and you return HTML templates from your backend through a HTTP request/response, you are mixing up templates between the frontend and the backend.
Why not just leave the templating stuff either in the frontend (i would suggest that), or in the backend (pretty intransparent imo)?
And if you keep templates in the frontend, why not just respond with JSON for requests to the backend. You do not even have to implement a RESTful structure, but keeping templates on one side makes your code more transparent.
This will pay back when someone else has to cope with your code (or even you yourself are re-entering your own code after a while)!
If you do it right, you will have small components with small templates, and best of all, if your code is imba, someone who doesn't know coding languages will be able to understand your templates and your logic! So additionally, keep your functions/methods as small you can.
You will eventually find out that maintaining, refactoring, reviewing, and adding features will be much easier compared to large functions/methods/classes and mixing up templating and logic between the frontend and the backend - and keep as much of the logic in the backend if your frontend needs to be more flexible (e.g. writing an android frontend or switching to a different frontend framework).
Philosophy, man :)
p.s.: you do not have to implement 100% clean code, because it is very expensive - especially if you have to motivate team members ;)
but: you should find a good balance between an approach to cleaner code and what you have (maybe it is already pretty clean)
check the book if you can and let it enter your soul:
https://de.wikipedia.org/wiki/Clean_Code
No, this is not a duplicate question. You see, there is a ton of questions and issues in SO and Github that prescribe that I add this directive to a tag that has [(ngModel)] directive and is not contained in a form. If I don't add it I get an error:
ERROR Error: No value accessor for form control with unspecified name attribute
Ok, the error goes away if I put this attribute there. BUT, wait! Nobody knows what it does! And Angular's doc doesn't mention it at all. Why do I need a value accessor when I know that I don't need it? How is this attribute connected to value accessors? What does this directive do? What is a value accessor and how do I use it?
And why does everybody keep doing things that they don't understand at all? Just add this line of code and it works, thank you, this is not the way to write good programs.
And then. I read not one but two huge guides about forms in Angular and a section about ngModel:
https://angular.io/guide/forms
https://angular.io/guide/reactive-forms
https://angular.io/guide/template-syntax#ngModel
And you know what? Not a single mention of either value accessors or ngDefaultControl. Where is it?
[ngDefaultControl]
Third party controls require a ControlValueAccessor to function with angular forms. Many of them, like Polymer's <paper-input>, behave like the <input> native element and thus can use the DefaultValueAccessor. Adding an ngDefaultControl attribute will allow them to use that directive.
<paper-input ngDefaultControl [(ngModel)]="value>
or
<paper-input ngDefaultControl formControlName="name">
So this is the main reason why this attribute was introduced.
It was called ng-default-control attribute in alpha versions of angular2.
So ngDefaultControl is one of selectors for DefaultValueAccessor directive:
#Directive({
selector:
'input:not([type=checkbox])[formControlName],
textarea[formControlName],
input:not([type=checkbox])[formControl],
textarea[formControl],
input:not([type=checkbox])[ngModel],
textarea[ngModel],
[ngDefaultControl]', <------------------------------- this selector
...
})
export class DefaultValueAccessor implements ControlValueAccessor {
What does it mean?
It means that we can apply this attribute to element (like polymer component) that doesn't have its own value accessor. So this element will take behaviour from DefaultValueAccessor and we can use this element with angular forms.
Otherwise you have to provide your own implementation of ControlValueAccessor
ControlValueAccessor
Angular docs states
A ControlValueAccessor acts as a bridge between the Angular forms API
and a native element in the DOM.
Let's write the following template in simple angular2 application:
<input type="text" [(ngModel)]="userName">
To understand how our input above will behave we need to know which directives are applied to this element. Here angular gives out some hint with the error:
Unhandled Promise rejection: Template parse errors: Can't bind to
'ngModel' since it isn't a known property of 'input'.
Okay, we can open SO and get the answer: import FormsModule to your #NgModule:
#NgModule({
imports: [
...,
FormsModule
]
})
export AppModule {}
We imported it and all works as intended. But what's going on under the hood?
FormsModule exports for us the following directives:
#NgModule({
...
exports: [InternalFormsSharedModule, TEMPLATE_DRIVEN_DIRECTIVES]
})
export class FormsModule {}
After some investigation we can discover that three directives will be applied to our input
NgControlStatus
#Directive({
selector: '[formControlName],[ngModel],[formControl]',
...
})
export class NgControlStatus extends AbstractControlStatus {
...
}
NgModel
#Directive({
selector: '[ngModel]:not([formControlName]):not([formControl])',
providers: [formControlBinding],
exportAs: 'ngModel'
})
export class NgModel extends NgControl implements OnChanges,
DEFAULT_VALUE_ACCESSOR
#Directive({
selector:
`input:not([type=checkbox])[formControlName],
textarea[formControlName],
input:not([type=checkbox])formControl],
textarea[formControl],
input:not([type=checkbox])[ngModel],
textarea[ngModel],[ngDefaultControl]',
,,,
})
export class DefaultValueAccessor implements ControlValueAccessor {
NgControlStatus directive just manipulates classes like ng-valid, ng-touched, ng-dirty and we can omit it here.
DefaultValueAccesstor provides NG_VALUE_ACCESSOR token in providers array:
export const DEFAULT_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DefaultValueAccessor),
multi: true
};
...
#Directive({
...
providers: [DEFAULT_VALUE_ACCESSOR]
})
export class DefaultValueAccessor implements ControlValueAccessor {
NgModel directive injects in constructor NG_VALUE_ACCESSOR token that was declared on the same host element.
export NgModel extends NgControl implements OnChanges, OnDestroy {
constructor(...
#Optional() #Self() #Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[]) {
In our case NgModel will inject DefaultValueAccessor. And now NgModel directive calls shared setUpControl function:
export function setUpControl(control: FormControl, dir: NgControl): void {
if (!control) _throwError(dir, 'Cannot find control with');
if (!dir.valueAccessor) _throwError(dir, 'No value accessor for form control with');
control.validator = Validators.compose([control.validator !, dir.validator]);
control.asyncValidator = Validators.composeAsync([control.asyncValidator !, dir.asyncValidator]);
dir.valueAccessor !.writeValue(control.value);
setUpViewChangePipeline(control, dir);
setUpModelChangePipeline(control, dir);
...
}
function setUpViewChangePipeline(control: FormControl, dir: NgControl): void
{
dir.valueAccessor !.registerOnChange((newValue: any) => {
control._pendingValue = newValue;
control._pendingDirty = true;
if (control.updateOn === 'change') updateControl(control, dir);
});
}
function setUpModelChangePipeline(control: FormControl, dir: NgControl): void {
control.registerOnChange((newValue: any, emitModelEvent: boolean) => {
// control -> view
dir.valueAccessor !.writeValue(newValue);
// control -> ngModel
if (emitModelEvent) dir.viewToModelUpdate(newValue);
});
}
And here is the bridge in action:
NgModel sets up control (1) and calls dir.valueAccessor !.registerOnChange method. ControlValueAccessor stores callback in onChange(2) property and fires this callback when input event happens (3). And finally updateControl function is called inside callback (4)
function updateControl(control: FormControl, dir: NgControl): void {
dir.viewToModelUpdate(control._pendingValue);
if (control._pendingDirty) control.markAsDirty();
control.setValue(control._pendingValue, {emitModelToViewChange: false});
}
where angular calls forms API control.setValue.
That's a short version of how it works.