Changing div inner HTML content by id in angular component method - javascript

I am trying to change inner HTML content of a div by id with another div in angular component method. I am able to call populateEndpointHomeContent() and get that content but not further content. Actually those methods populateAddEndpoint() and populateAddEndpointForm are not getting called on click. I am not getting any console error also. Any idea how I can get this?
endpoint.component.html
<div id="endpoint_home"></div>
<div id="endpoint_home_content" style="display:none">
<button class="btn btn-sm" (click)="populateAddEndpoint();">+ Add Endpoint</button>
</div>
<!-- Add Endpoint DIVS Starts -->
<div id="add_endpoint_home" style="display:none">
<form #endpointForm="ngForm">
<section class="form-block">
<div class="form-group">
<label for="endPointType">Select Endpoint Type</label>
<div class="select">
<select id="endPointType" (change)="populateAddEndpointForm(this.value);">
<option>MACHINE</option>
<option>K8S_CLUSTER</option>
<option>AWS</option>
<option>DOCKER</option>
<option>VCENTER</option>
<option>WAVEFRONT</option>
<option>VRNI</option>
</select>
</div>
</div>
<div id="add_endpoint_form"></div>
<button type="submit" class="btn btn-primary">ADD</button>
</section>
</form>
</div>
<div id="add_machine_form" style="display:none">
<div class="form-group">
<label for="name">Endpoint Name</label>
<input type="text" placeholder="Endpoint Name" size="42" id="name" name="name" [(ngModel)]="name" required>
</div>
<div class="form-group">
<label for="credentialsName">Credential Name</label>
<div class="select">
<select id="credentialsName">
<option>MACHINE</option>
</select>
</div>
</div>
<button type="button" class="btn btn-primary">ADD CREDENTIAL</button>
<div class="form-group">
<label for="host">Machine Host/IP</label>
<input type="text" placeholder="0.0.0.0" size="42" id="host" name="host" [(ngModel)]="host" required>
</div>
<div class="form-group">
<label for="sshPort">SSH Port</label>
<input type="number" placeholder="22" size="42" id="sshPort" name="sshPort" [(ngModel)]="sshPort" required>
</div>
<div class="form-group">
<label for="timeout">SSH Timeout</label>
<input type="number" placeholder="60" size="42" id="timeout" name="timeout" [(ngModel)]="timeout" required>
</div>
<div class="form-group">
<label for="osType">OS Type</label>
<div class="select">
<select id="osType">
<option>WINDOWS</option>
<option>LINUX</option>
</select>
</div>
</div>
</div>
<!-- Add Endpoint DIVS Ends -->
EndpointComponent
import { Component, OnInit } from '#angular/core';
import { EndpointService } from './endpoint.service';
#Component({
selector: 'app-endpoint',
templateUrl: './endpoint.component.html',
styleUrls: ['./endpoint.component.scss']
})
export class EndpointComponent implements OnInit {
constructor(private endpointService: EndpointService) { }
public wavefrontendpoints: any;
ngOnInit() {
this.populateEndpointHomeContent();
this.endpointService.getAllEndpoints().subscribe(res => this.wavefrontendpoints = res.response[0]);
}
public populateEndpointHomeContent() {
document.getElementById('endpoint_home').innerHTML = document.getElementById('endpoint_home_content').innerHTML;
}
public populateAddEndpoint() {
console.log('Inside populateAddEndpoint...');
document.getElementById('endpoint_home').innerHTML = document.getElementById('add_endpoint_home').innerHTML;
}
public populateAddEndpointForm(endPointType) {
console.log('Inside populateAddEndpointForm...');
if(endPointType === 'MACHINE') { document.getElementById('add_endpoint_form').innerHTML = document.getElementById('add_machine_form').innerHTML; }
}
}

Trying to render HTML content from its innerHTML will not have its prototype functions work.
Your HTML will be visible, but it won't make their click events trigger, because innerHTML only contains the HTML markup, not the function or event prototypes.
Go through Angular's Guide on Dynamic Component Loader, which is about loading dynamic content in an HTML page.

Related

I'm trying to discard a bootstrap modal using Angular 6 when the server receives the data

Well, this is the component where I'm trying to create all the content. It is a crud that saves the data when and what I want is for the modal to disappear.
<div class="container">
<div class="table-wrapper">
<div class="table-title">
<div class="row">
<div class="col-sm-6">
<h2>Codigos De <b>Acceso.</b></h2>
</div>
<div class="col-sm-6">
<i class="material-icons"></i> <span>Agregar nuevo codigo</span>
</div>
</div>
</div>
<div class='col-sm-12 pull-right d-flex flex-row-reverse'>
<div id="custom-search-input">
<div class="input-group">
<input type="text" class="form-control" placeholder="Buscar" aria-label="Input group example" aria-describedby="btnGroupAddon2">
<div class="input-group-append">
<button class="btn btn-primary" id="btnGroupAddon2"><i class="fas fa-search"></i></button>
</div>
</div>
</div>
</div>
<div class='clearfix'></div>
<hr>
<div id="loader"></div>
<div id="resultados"></div>
<div class='outer_div'></div>
</div>
</div>
<!-- Add Modal HTML -->
<div id="addProductModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form #dataForm="ngForm" (ngSubmit)="addData(dataForm)">
<div class="modal-header">
<h4 class="modal-title">Añadir Codigo</h4>
<button type="button" class="close" data-dismiss="modal" id="dismiss" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Código</label>
<input type="text" name="code" class="form-control" #code="ngModel" [(ngModel)]="dataService.selectedData.code" required >
</div>
<div class="form-group">
<label>Dirección</label>
<input type="text" name="direction" class="form-control" #direction="ngModel" [(ngModel)]="dataService.selectedData.direction" required>
</div>
<div class="form-group">
<label>Comentario</label>
<input type="text" name="comment" class="form-control" #comment="ngModel" [(ngModel)]="dataService.selectedData.comment" required>
</div>
<div class="form-group">
<label>Tech #</label>
<input type="number" name="tech" class="form-control" #tech="ngModel" [(ngModel)]="dataService.selectedData.tech" required>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-secondary" data-dismiss="modal" value="Cancelar">
<input type="submit" class="btn btn-primary" value="Guardar datos">
</div>
</form>
</div>
</div>
</div>
<div class="center">
and this is my ts file:
import { Component, OnInit } from '#angular/core';
import { Data } from '../../models/data' // La ruta puede ser distinta.
import { DataService } from '../../services/data.service';
import { NgForm } from '#angular/forms';
#Component({
selector: 'app-datas',
templateUrl: './datas.component.html',
styleUrls: ['./datas.component.css'],
providers: [DataService]
})
export class DatasComponent implements OnInit {
constructor(private dataService: DataService) { }
ngOnInit() {}
addData(form: NgForm) {
this.dataService.postData(form.value)
.subscribe(res => {
this.resetForm(form);
})
}
/*
close(form?: NgForm){
if
}*/
resetForm(form?: NgForm) {
if(form){
form.reset();
var dismiss = document.querySelector('#addProductModal');
console.log(dismiss);
this.dataService.selectedData = new Data();
}
}
}
As you can see, that last method is called resetForm, I tried to clean the form when the data is sent and I have achieved it, but what I need is that the modal is discarded. Anyone have an idea?
NPM uninstall jQuery right away. Don't use the JavaScript version of bootstrap, install ngx-bootstrap and use the Angular components. They play much nicer with Angular. Your component should not be inspecting the DOM with querySelector and you shouldn't use any jQuery. If you rewrite the component using ngx-bootstrap you will be able to get an instance of an Angular modal component and call close.
https://valor-software.com/ngx-bootstrap/#/modals

Reset forms on angular 2

im trying to get some values in forms using the submit event. But i can´t reset those forms later. Im trying to use an id called "myForm" and an onclick function
<form (Submit)="addMarker()" id="myForm">
<div class="row">
<div class="col">
<input type="text" [(ngModel)]="lat" name="lat" class="form-control" placeholder="Latitud">
</div>
<div class="col">
<input type="text" [(ngModel)]="lng" name="lng" class="form-control" placeholder="Longitud">
</div>
<div class="col-3">
<button type="submit" class="btn btn-primary" onclick="myFunction()">Agregar Marcador</button>
</div>
</div>
</form>
Script:
function myFunction() {
document.getElementById("myForm").reset();
}
In your HTML:
<form (submit)="addMarker(myForm)" id="myForm" #myForm="ngForm"> // <-- Notice the "#"
<div class="row">
<div class="col">
<input type="text" [(ngModel)]="lat" name="lat" class="form-control" placeholder="Latitud">
</div>
<div class="col">
<input type="text" [(ngModel)]="lng" name="lng" class="form-control" placeholder="Longitud">
</div>
<div class="col-3">
<button type="submit" class="btn btn-primary">Agregar Marcador</button>
</div>
</div>
</form>
In your ts:
Import NgForm first by adding:
import { NgForm } from '#angular/forms';
Function to reset the form:
addMarker(form: NgForm) {
//do something and then reset the form
form.resetForm();
}
For Angular 2 Final, we now have a new API that cleanly resets the form:
#Component({...})
class App {
form: FormGroup;
...
reset() {
this.form.reset();
}
}
This API not only resets the form values, but also sets the form field states back to ng-pristine and ng-untouched.

Submit Button does not work / react

I am new to Angular 2 and Typescript but I am trying to build a web app.
I build some input fields and I want to log them to the console after submitting them via a button. But my button does not really work or react.
Does anyone have an idea what is the problem with my code?
Here is my code:
app.component.html
<div class="panel panel-primary">
<div class="panel-heading">Status</div>
<div class="panel-body">
<h3>{{title}}</h3>
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm.value)">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ngModel>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" ngModel>
</div>
<div class="form-group">
<label>Street</label>
<input type="text" class="form-control" name="street" ngModel>
</div>
<div class="form-group">
<label>PLZ</label>
<input type="text" class="form-control" name="plz" ngModel>
</div>
</form>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
app.component.ts
import { Component, style } from '#angular/core';
import { TutorialsComponent } from './tutorial.component';
import { SteliosComponent } from './stelios.component';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public title ="Das ist die erste Componente"
public childData: string;
onSubmit(value: any){
console.log(value);
}
}
Your button isn't in your form. Put it in your form and you're good to go !
You have to associate the submit button with the form.
This is usually done by putting the <button> element inside the <form> element.
You could do that by moving it to just before </form>.
Alternatively, you could use the form attribute:
<button form="id_of_form_element_goes_here" type="submit" class="btn btn-primary">Submit</button>
… but browser support for that is weaker.
Move the submit button inside the form.
<form>
<button type="submit" class="btn btn-primary">Submit</button>
</form>

Can anyone tell me how to use addClass and removeClass actually my code is not working

i have a case here. when clicked on button i want the class to be change for example if the button is clicked i want hide-tab to be removed and at the same time i want to add show-tab class this is my jquery code please help me with it
$(document).ready(function() {
$('#button').on('click', function() {
$('.form-group').removeClass('hide-tab');
$(this).addClass('show-tab');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-container">
<form class="fs-form fs-form-full">
<div class="form-group">
<label class="field">What is your name?</label>
<input type="text" class="form-control">
<div class="border"></div>
</div>
<div class="form-group hide-tab">
<label class="field">What is your mobile number?</label>
<input type="text" class="form-control">
<div class="border"></div>
</div>
<div class="form-group hide-tab">
<label class="field">What is your email address?</label>
<input type="email" class="form-control">
<div class="border"></div>
</div>
<div class="form-group hide-tab">
<label class="field">What type of event do you want us to organize?</label>
<select class="form-control">
<option>Dance Events</option>
<option>Birthday Events</option>
<option>Family Gathering Events</option>
<option>Marathon Events</option>
<option>Awards Ceremony</option>
<option>Art Competition</option>
</select>
<div class="border"></div>
</div>
<div class="form-group hide-tab">
<label class="field">Breif your thoughts</label>
<textarea class="form-control"></textarea>
<div class="border"></div>
</div>
<div class="form-group hide-tab">
<label class="field">Schdule Meeting</label>
<input type="date" class="form-control">
<div class="border"></div>
</div>
<div class="form_group">
<button type="submit" class="btn btn-primary" id="button">Continue</button>
</div>
</form>
</div>
Since your button type is submit.So changes happen but at-once form is processed and everything is reloaded. That's why you are unable to see the changes.
Use preventDefault() like below:-
$(document).ready(function() {
$('#button').on('click', function(e) {
e.preventDefault();
$('.form-group').removeClass('hide-tab'); // remove hide-tab class from all elements having form-group class
$(this).addClass('show-tab'); // this will add class to the button only not to others
});
});

Attaching an event to new element in Angular2

I need to duplicate a new row on the click of + button. That new row contains a - button which will in turn delete that newly created row. So the problem is I could attach a click event to that new - button.
Below is the ts which contains the form :
import { Component, OnInit, ViewEncapsulation, ElementRef } from '#angular/core';
import { MailSegmentObject } from './mailSegmentObject';
import { MailSegmentRule } from './mailSegmentRule';
#Component({
selector : 'segment-form',
templateUrl : 'app/html/createSegment.html',
styleUrls : ['node_modules/bootstrap/dist/css/bootstrap.min.css'],
encapsulation : ViewEncapsulation.Native
})
export class CreateSegmentComponent {
counter : number = 0;
segment : MailSegmentObject = new MailSegmentObject();
addNewRule() : void {
var origElem = document.getElementById("mandatoryRule");
var copyElem = <HTMLDivElement>origElem.cloneNode(true);
copyElem.setAttribute("id", "mandatoryRule_" + (this.counter++));
copyElem.innerHTML += "<div class=\"col-sm-1\"><button type=\"button\" class=\"btn btn-default\" (click)=\"deleteRule(this)\">-</button></div>";
origElem.parentElement.appendChild(copyElem);
}
deleteRule(elem) : void {
console.log("asdasdasdasdasd");
elem.parentElement.removeChild(elem);
}
}
and html is:
<div class="container" style="margin-top: 15px;">
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="Segment Name">Segment Name</label>
<div class="row">
<div class="col-sm-12">
<input type="text" class="form-control" id="segmentNameInput" placeholder="Segment Name">
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Select Property</label>
<div class="row rule" id="mandatoryRule">
<div class="col-sm-3">
<select class="form-control">
</select>
</div>
<div class="col-sm-3">
<select class="form-control">
</select>
</div>
<div class="col-sm-3">
<input type="text" class="form-control">
</div>
</div>
<div class="col-sm-1">
<button type="button" class="btn btn-default" (click)="addNewRule(this)">+</button>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
Kindly help me out.
Thanks.
This is written completely against the concept of angular2. You should use *ngFor on a collection of lines. Never ever -ever- use things like: getElementById, cloneNode, innerHTML, appendChild, removeChild.
My suggestion is that you take a closer look to the tutorials and cook book provided at angular.io, because I'm sorry, with the current state of your code, you are asking for a complete rewrite

Categories