New Line not working properly in Angular 2 editable div - html

I have a contenteditable div that works great until I assign the changed text back into initial variable. When editing and I press enter, a new line appears properly in the editable div, but does not get stored into 'name'. The next character typed ends up at the end of the previous line, and the cursor goes to the beginning of the first line. If I remove the (input) line, the div behaves properly, but 'name' is not updated. How do I get the div to behave properly and update 'name'?
Plunk Demo
import {Component, NgModule} from '#angular/core'
import {BrowserModule} from '#angular/platform-browser'
#Component({
selector: 'my-app',
template: `
<div style="white-space: pre-wrap;"
[textContent]=name
(input)="name=$event.target.textContent"
contenteditable>
</div>
<div style="white-space: pre-wrap;">{{name}}</div>
`,
})
export class App {
name:string;
constructor() {
this.name = `TEST`
}
}
#NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
Expected Result:
Test
Test
Actual Result:
estTestT

With some little changes you can make it work.
Change textContent attribute to innerText.
Set the the innerText value value in ngOnInit and forgo ngModel.
Typescript:
#ViewChild('myEditable') private myEditable;
name:string;
constructor() {
this.name = 'I am editable';
}
ngOnInit(){
this.myEditable.nativeElement.innerText = this.name;
}
HTML:
<div #myEditable contentEditable (input)="name=$event.target.innerText"></div>
<div style="white-space:pre">{{name}}</div>
Demo

Related

Insert HTML into string

Using Angular 5 and Firebase, I have created a review website that allows users to create reviews on the CreateComponent and read them on the ReviewComponent. I'd like the body of the review to be able to contain HTML for links or images.
The ReviewComponent pulls the body of the review with:
<p style="margin-bottom: 2rem; white-space: pre-wrap;">{{review.body}}</p>
I am using pre-wrap to maintain the body's line breaks.
An example input from the CreateComponent would be:
I already can’t wait to see what comes next.
When I inspect the output of the body I see this:
<p _ngcontent-c1 style="margin-bottom: 2rem; white-space: pre-wrap;">I already can’t wait to see <a href="http://www.ign.com/articles/2017/11/30/marvels-the-avengers-infinity-war-trailer-breakdown">what comes next.</a></p>.
How can I change the HTML to enable the string to work correctly with links and images?
Binding review.body to [innerHTML] corrected this.
<p style="margin-bottom: 2rem; white-space: pre-wrap;">{{review.body}}</p>
is now
<p style="margin-bottom: 2rem; white-space: pre-wrap;" [innerHTML]="review.body"></p>
Here is solutions for your issue:
https://plnkr.co/edit/VHvVpvnTeoGWsA0d3eex?p=preview
Here is code:
//our root app component
import {Component, NgModule, VERSION, Pipe, PipeTransform, ChangeDetectorRef } from '#angular/core'
import {BrowserModule} from '#angular/platform-browser'
import { FormsModule } from '#angular/forms';
#Component({
selector: 'my-app',
template: `
<div [outerHTML]='selectedValue | html'></div>
`,
})
export class App {
selectedValue: string = 'I already can’t wait to see what comes next.';
constructor(private cd: ChangeDetectorRef) {
}
}
#Pipe({
name: 'html'
})
export class HtmlPipe implements PipeTransform {
transform(value: string) {
return `<div>${value}</div>`;
}
}
#NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ App, HtmlPipe ],
bootstrap: [ App ]
})
export class AppModule {}
You could write pipe for this application, like in this article:
How to allow html in return of angular2 pipe?

Angular 5 issue with contenteditable and input in firefox and safari

So I'm creating a table with content-editable cells, I need at the same time to update the visual and the typescript code, unfortunately all alternatives I found didn't work, here is a plunker with identical issue:
https://plnkr.co/edit/PCXNFSUqiHrYedx4E4mW?p=preview
import {Component, NgModule, VERSION} from '#angular/core'
import {BrowserModule} from '#angular/platform-browser'
#Component({
selector: 'my-app',
template: `
<div contenteditable='true'
(input)='name=$event.target.innerText'
[(innerText)]='name'>
name
</div>
<br>
<div contenteditable='true'
(input)='name=$event.target.innerHtml'
[(innerHtml)]='name'>
name
</div>
<br>
<div contenteditable='true'
(input)='name=$event.target.textContent'
[(textContent)]='name'>
name
</div>
`,
})
export class App {
name:string;
constructor() {
this.name = `Angular! v${VERSION.full}`
}
}
#NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
It works well with google chrome and opera, safari and mozilla wrights the text backwards with textContent and innerText, and the value become undefined with innerHtml.
#Update
For my issue I end up using input-field inside the cells
<td [class.active]="selectedCell.row === rowIndex && selectedCell.colunm === 3"
(click)="setSelectedCell(rowIndex, 3, true)"
class="lassoer-info">
<input [id]="'entity' + rowIndex"
(keydown)="onkeyDown($event)"
[(ngModel)]="rowData.entity"
[disabled]="rowData.inscriptionId || !canEdit"
type="text"
class="input-field">
</td>
I'm just starting with Angular but I think I can spot one mistake. In Javascript it should be innerHTML instead of innerHtml (HTML in upper case).

Hide elements using Typescript

I'm new to Typescript and Angular Material. I want to hide elements inside elements like this.
<div id="abc">
<div id="123">
<p>Hello!</p>
</div>
<p>World</p>
</div>
<div id="def">
<p>Hello World</p>
</div>
I want to hide div block(id:123).I tried in this way.
var formElement = <HTMLFormElement>document.getElementById('123');
formElement.style.display='block';
It gets an error saying Cannot read property 'style' of null.... How can I solve this problem.
This is not the way to hide elements in Angular. Bind your element's style attribute to a boolean, like this:
<form [style.display]="isVisible ? 'block' : 'none'">... contents</form>
And in your component class:
this.isVisible = false; // whenever you need to hide an element
Or you can use *ngIf:
<form *ngIf="isVisible">... contents</form>
Please, note that *ngIf removes the node and its children completely from the DOM tree completely if the conditions turns to false, and fully recreates them from scratch when the condition turns true.
You can access the dom element using ViewChild with #localvariable as shown here,
import {Component, NgModule,ViewChild,ElementRef} from '#angular/core'
import {BrowserModule} from '#angular/platform-browser'
#Component({
selector: 'my-app',
template: `
<div id="abc">
<div #id id="123">
<p>Hide!</p>
</div>
<p>World</p>
</div>
<div id="def">
<p>Hello World</p>
</div>
`,
})
export class App {
name:string;
#ViewChild('id') el:ElementRef;
constructor() {
this.name = `Angular! v${VERSION.full}`
}
ngAfterViewInit()
{
this.el.nativeElement.style.display='none';
console.log(this.el.nativeElement);
}
}
#NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
#Component({
selector: 'my-app',
template: `
<div #id>
<p>Hide This!</p>
</div>
<div>
<p>Hello World</p>
</div>
`,
})
export class AppComponent {
#ViewChild('id') id:ElementRef;
constructor() {}
ngOnInit()
{
this.id.nativeElement.hidden=true;
}
}
The simplest way to hide elements using DOM is
document.getElementById('123').hidden = true;
in typescript.

Angular2 dynamically generating Reactive forms

I have a concept question and would like some advice.
So I have a component, myFormArray, which is a reactive form. It takes in an input array, and creates a number of FormControls accordingly.
#Component({
selector: 'myFormArray',
templateUrl: 'formarray.component.html'
})
export class FormArrayComponent{
#Input() classFields: any[];
userForm = new FormGroup();
ngOnInit(){
// psuedocode here, but I know how to implement
for (# of entries in classFields)
userForm.FormArray.push(new FormControl());
}
Now, in my parent html, I will be dynamically generating multiple myFormArrays. If that is confusing, assume I'm doing this:
<myFormArray [classFields] = "element.subArray"/>
<myFormArray [classFields] = "element2.subArray"/>
<button (click) = "save()"> //I don't know how to implement this!
And at the very end of the page, I want a save button, that can somehow grab all the values the user inputs in to all the forms, and pushes all this data to an array in a Service component. I'm not sure exactly how to do this part. Note that I don't want individual submit buttons for each dynamically generated form component.
How would I implement this functionality? Thanks!
Your start is good, but you have to write your source code differently.
Instead of this example app.components.ts is main component and my-array.component.ts is child component.
Our test data
classFields1: any[] = ['firstname', 'lastname', 'email', 'password'];
classFields2: any[] = ['country', 'city', 'street', 'zipcode'];
Step 1. Use FormBuilder for form creation (app.component.ts)
You must import FormBuilder and FormGroup from #angular/forms like this:
import { FormBuilder, FormGroup } from '#angular/forms';
and then define in constructor:
constructor(private formBuilder: FormBuilder) { }
Step 2. Define new empty FormGrooup
Now you can define new empty FormGroup in ngOnInit like this:
ngOnInit() {
this.myForm = this.formBuilder.group({});
}
Step 3. Create FormControls dynamically (app.component.ts)
Now you can start with dynamically creation of your FormControls by iteration of classFields. For this I would recommend to create own function. This function gets two parameter: arrayName and classFields. With arrayName we can set custom name of our FormArray-control. classFields-Array we will use for iteration. We create constant variable for empty FormArray, which we called arrayControls. After this we iterate over classFields and create for each element FormControl, which we called control, and push this control into arrayControls. At the end of this function we add our arrayControls to our Form with custom name by using arrayName. Here is an example:
createDynamicArrayControls(arrayName: string, classFields: any[]) {
const defaultValue = null;
const arrayControls: FormArray = this.formBuilder.array([]);
classFields.forEach(classField => {
const control = this.formBuilder.control(defaultValue, Validators.required);
arrayControls.push(control);
})
this.myForm.addControl(arrayName, arrayControls);
}
Import FormControl and FormArray from #angular/forms. Your import line should be like this:
import { FormBuilder, FormGroup, FormArray, FormControl } from '#angular/forms';
Now call createDynamicFormControls-Function in ngOnInit.
Step 4. HTML Template for this dynamic Form (app.component.html)
For this example I create following template:
<h1>My Form</h1>
<form [formGroup]="myForm">
<div formGroupName="test1">
<app-my-array [classFields]="classFields1" [arrayFormName]="myForm.controls.test1"></app-my-array>
</div>
<div formGroupName="test2">
<app-my-array [classFields]="classFields2" [arrayFormName]="myForm.controls.test2"></app-my-array>
</div>
<button type="button" (click)="saveForm()">Submit</button>
</form>
Here we have new div element with formGroupName. This group name is our arrayName in our form. We give our form arrays via #Input to my-array.component.
Step 5. MyArrayComponent
Now this component is very simnple:
import { Component, OnInit, Input } from '#angular/core';
import { FormGroup } from '#angular/forms';
#Component({
selector: 'app-my-array',
templateUrl: './my-array.component.html',
styleUrls: ['./my-array.component.css']
})
export class MyArrayComponent implements OnInit {
#Input() classFields: any[];
#Input() arrayFormName: FormGroup;
constructor() { }
ngOnInit() { }
}
Here we have only two #Input varibales. (I know, this variable can have a better names :-) ).
Step 6. HTML for MyArrayComponent
<div [formGroup]="arrayFormName">
<div *ngFor="let class of arrayFormName.controls; let index = index;">
<label [for]="classFields[index]">{{ classFields[index] }}</label>
<input type="text" [id]="classFields[index]" [formControlName]="index" />
</div>
</div>
<br>
And here is working example on Stackblitz: https://stackblitz.com/edit/angular-wawsja
If you have some question ask me in comments or read the Angular documentation abour Reactive Forms here.

how can i flash image by hovering on button with the help of mouseover option in angularjs2?

What I want to do is when I hover on the 'click me' button then it should show an image on the web page and when i unhover it should not show any image with the help of mouseover option
here is what i tried to do in app.component.ts and my.component.ts files
here is the code for app.component.ts :
import { Component } from '#angular/core'; //importing components from angular
import { MyComponent } from './my.component'; //importing components from my.component
#Component({
selector: 'my-app',
template: `<h1> Hi Buddy!! </h1>
<mytag></mytag>`,
directives: [MyComponent] //adding directives from mycomponents
})
export class AppComponent { }
and here is the code for my.component.ts:
import { Component } from "#angular/core";
#Component({
selector:'mytag',
template: `<button (mouseover)="<img [src]="image"> " >click me</button>` // here i tried to flash image by hovering
})
export class MyComponent{
public image="http://lorempixel.com/400/200";
myclick(klm){
console.log(klm);
}
}
so what changes should i make in the class or meta data of my.component.ts in order to do so
You can use Angular Animations module to achieve the same.
Make the below changes to your MyComponent:
import { Component } from '#angular/core'
import { trigger, state, style, transition, animate, keyframes, group } from '#angular/animations';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
#Component({
selector:'mytag',
template: `<button (mouseover)="toggleOnOff()">click me</button>
<img [src]="image" [#switchImageDisplay]="showImage"/>
`
,
animations: [
trigger("switchImageDisplay",[
state("show", style({
display : 'block'
})),
state("hide", style({
display : 'none'
})),
transition('show <-> hide',[animate('0s')]),
])
]
})
export class SwitchDisplayComponent {
public image="http://lorempixel.com/400/200";
public showImage : string;
toggleOnOff(){
console.log("Previous display value is",this.showImage);
this.showImage = (this.showImage === "show") ? "hide" : "show";
console.log("Current display value is",this.showImage);
}
}
Explanation:
toggleOnOff() function sets a string variable showImage as show and hide.
In Animations we create a trigger and give it a name. In our case we have named it as "switchImageDisplay". We declared two states in the animation trigger that is "show" and "hide". In those states we defined what CSS to be used. Finally we defined a transition, which is 2 ways binded and is performed in 0 seconds. If you want the image to be hidden over a period of time increase the time.
In template code, we have binded the img tag to the animation using the code [#switchImageDisplay]="showImage". Based on the "showImage" value, the animation "switchImageDisplay"'s state is defined.
Import the import { BrowserAnimationsModule } from '#angular/platform-browser/animations'; in your app.module.ts and in the imports array as well.