Selenium Dom Is Not Changed After Execution Of Angular Ng If Condition

Find the data you need here

We provide programming data of 20 most popular languages, hope to help you!

Previous PostNext Post

Selenium DOM is not changed after execution of Angular ng-if condition

Find centralized, trusted content and collaborate around the technologies you use most.

<p ng-if="!old_email" style="line-height: 20px; font-weight: normal;"><b>Hi,</b><br><br>
    We have created a new account with &rsquo;{{ new_email }}&lsquo;, for you on<br> Plobal Apps to preview and test your app and mailed you the details. Please check your inbox.
</p>

<p ng-if="new_user && old_email" style="line-height: 20px; font-weight: normal;"><b>Hi,</b><br><br>
  We have created a new account with &rsquo;{{ new_email }}&lsquo;, for you on<br> Plobal Apps to preview and test your shopify app and mailed you the details. Please check your inbox.
  <br />
  You have been logged out of the previous account with &rsquo;{{ old_email }}&lsquo;.
</p>

<p ng-if="existing_user && old_email" style="line-height: 20px; font-weight: normal;"><b>Hi,</b><br><br>
  We have logged you in with &rsquo;{{ new_email }}&lsquo;, on Plobal Apps to preview and test your shopify app.
  <br />
  You have been logged out of the previous account with &rsquo;{{ old_email }}&lsquo;.
</p>
<!-- ngIf: !old_email -->

<!-- ngIf: new_user && old_email -->

<!-- ngIf: existing_user && old_email --><p class="ng-binding ng-scope" ng-if="existing_user &amp;&amp; old_email" style="line-height: 20px; font-weight: normal;"><b>Hi,</b><br><br>
  We have logged you in with ’[email protected]‘, on Plobal Apps to preview and test your shopify app.
  <br>
  You have been logged out of the previous account with ’[email protected]‘.
</p><!-- end ngIf: existing_user && old_email -->
<p ng-if="!old_email" style="line-height: 20px; font-weight: normal;"><b>Hi,</b><br><br>
  We have created a new account with ’{{ new_email }}‘, for you on<br> Plobal Apps to preview and test your app and mailed you the details. Please check your inbox.
</p>

<p ng-if="new_user &amp;&amp; old_email" style="line-height: 20px; font-weight: normal;"><b>Hi,</b><br><br>
  We have created a new account with ’{{ new_email }}‘, for you on<br> Plobal Apps to preview and test your shopify app and mailed you the details. Please check your inbox.
  <br>
  You have been logged out of the previous account with ’{{ old_email }}‘.
</p>

<p ng-if="existing_user &amp;&amp; old_email" style="line-height: 20px; font-weight: normal;"><b>Hi,</b><br><br>
  We have logged you in with ’{{ new_email }}‘, on Plobal Apps to preview and test your shopify app.
  <br>
  You have been logged out of the previous account with ’{{ old_email }}‘.
</p>
ng-if="new_user &amp;&amp; old_email"
ng-if="new_user && old_email"
&amp;&amp;
ng-if="existing_user &amp;&amp; old_email"
&amp;&amp;

Ng-If in Angular With Multiple Conditions

A ngIf directive is a powerful tool in AngularJS ( https://angular.io/features) that lets you dynamically show and hide HTML content. It can also show or hide content based on an expression. If the ng-if directive’s statement evaluates to a TRUE Boolean value, the element is inserted into the HTML view; otherwise, it is deleted from the DOM

<element ng-if="expression"**>
</element>**
if(display){
  <div>I am here</div>
}

else{
  <div>
   I am not here
  </div>
 }
<ng-template [ngIf]="display">

  <div>I am Playing</div>

</ng-template> 
<div *ngIf="display" class="information" id="info">
  I am Playing
</div> 
 
 <ng-template [ngIf]="display">
    <div class="information" id="info">
      I am Playing
    </div>
 </ng-template>
<div *ngIf="isCar && isBike">

 <span>{{Name}}</span>

</div>
 <div *ngIf="isCar || isBike">
   // Show Price comparison chart
 </div>
<div *ngIf="!isCar">
	//Show the Prices of Bikes
</div>
<div *ngIf="Items.type = 'Cosmetics'">
// Show the Cosmetics items
</div>

Angular dom not updating on changes

Getting issues with the view not recognizing value changes on a component I've tried using ChangeDetectorRef and still not getting any results. tried a bunch of thing and iv'e spent way to much time on something that i think should just work. I have a feeling its something to do with the way the gapi is handeling the onsucess function but I've also tried binding it …

<mat-toolbar color="">
    <span routerLink="">Hub</span>
  <span class="spacer"></span>
  <ul >
    <li [hidden]="!userIsAuthenticated" >
      <a mat-button (click)="onLogout()" routerLinkActive="mat-accent">LogOut</a>
    </li>
    <li [hidden]="userIsAuthenticated">
      <app-google-signin></app-google-signin>
    </li>
  </ul>
</mat-toolbar>

import {AfterViewInit, ChangeDetectorRef, Component, OnDestroy, OnInit} from '@angular/core';
import {AuthService} from '../auth/auth.service';
import {Subscription} from 'rxjs';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit, OnDestroy {
  private userIsAuthenticated = false;
  private loggingIn = false;
  private authStatusListenerSub: Subscription;
  private loggingInSub: Subscription;

  constructor(private authService: AuthService, private ref: ChangeDetectorRef) {
  }

  ngOnInit() {
    this.userIsAuthenticated = this.authService.getIsAuthenticated();
    this.loggingInSub = this.authService.getLoggingInListener().subscribe(loggingIn => {
      this.loggingIn = loggingIn
      console.log(`Logging In: ${loggingIn}`)
      this.ref.markForCheck()
    })

    this.authStatusListenerSub = this.authService.getAuthStatusListener().subscribe(isAuthenticated=>{
      this.userIsAuthenticated = isAuthenticated
      console.log(`Authenticated: ${isAuthenticated}`)
    });

  }


  ngOnDestroy() {
    this.authStatusListenerSub.unsubscribe();
  }
}


import {EventEmitter, Injectable, Output} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Subject} from 'rxjs';

declare const gapi: any;


@Injectable({
  providedIn: 'root'
})
export class AuthService {
  public CLIENT_ID = '[clientId]';
  private isAuthenticated = false;
  private loggingIn = false;

  @Output() authStatus = new EventEmitter<boolean>()

  private authStatusListener = new Subject<boolean>();
  private loggingInListener = new Subject<boolean>();

  constructor(private http: HttpClient) {
  }

  onGoogleSignIn(googleUser) {
    this.loggingIn = true;
    this.loggingInListener.next(true)
    const googleToken = googleUser.getAuthResponse().id_token;
    this.http.post<{ message: string, access: boolean }>(
      '[login url]',
      {loginToken: googleToken},
      {withCredentials: true})
      .subscribe(
        res => {
          console.log(res.message);
          this.loggingIn = false;
          this.loggingInListener.next(false)
          this.isAuthenticated = true;
          this.authStatusListener.next(true);
        },
        (err) => {
          this.loggingIn = false;
          this.loggingInListener.next(false)
          this.logout();
        });
  }


  getIsAuthenticated() {
    return this.isAuthenticated;
  }

  getAuthStatusListener() {
    return this.authStatusListener.asObservable();
  }

  getLoggingInListener() {
    return this.loggingInListener.asObservable()
  }
}
import {AfterViewInit, Component, ElementRef, OnInit} from '@angular/core';
import {AuthService} from '../auth.service';

declare const gapi: any;


@Component({
  selector: 'app-google-signin',
  templateUrl: './google-signin.component.html',
  styleUrls: ['./google-signin.component.scss']
})
export class GoogleSigninComponent implements OnInit, AfterViewInit {
  public auth2: any;

  constructor(
    private element: ElementRef,
    private authService: AuthService,
  ) {
  }

  ngOnInit() {

  }

  ngAfterViewInit() {
    this.googleInit();
  }


  public googleInit() {
    gapi.load('auth2', () => {
      this.auth2 = gapi.auth2.init({
        client_id: this.authService.CLIENT_ID,
        cookie_policy: 'single_host_origin',
      });

      const element = gapi.signin2.render('app-google-signin', {
        scope: 'profile email',
        longtitle: true,
        theme: 'dark',
        onsuccess: this.authService.onGoogleSignIn.bind(this.authService),
        onfailure: err => console.log(err)
      });
    });
  }

}
 @Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush // add this 
})
export class HeaderComponent implements OnInit, OnDestroy {
  private userIsAuthenticated = false;
  private loggingIn = false;
  private authStatusListenerSub: Subscription;
  private loggingInSub: Subscription;

  constructor(private authService: AuthService, private cdr: ChangeDetectorRef) {
  }

  ngOnInit() {
    this.userIsAuthenticated = this.authService.getIsAuthenticated();
    this.loggingInSub = this.authService.getLoggingInListener().subscribe(loggingIn => {
      this.loggingIn = loggingIn
      console.log(`Logging In: ${loggingIn}`)
      this.cdr.detectChanges(); // *trigger change here*
    })

    this.authStatusListenerSub = this.authService.getAuthStatusListener().subscribe(isAuthenticated=>{
      this.userIsAuthenticated = isAuthenticated
      console.log(`Authenticated: ${isAuthenticated}`)
    });

  }


  ngOnDestroy() {
    this.authStatusListenerSub.unsubscribe();
  }
}

How to do DOM Manipulation properly in Angular?

Steps: Step 1: Add ng-container tag into the template file. <ng-container #viewcontainer></ng-container>. Step 2: Add viewchild query to select element. @ViewChild(‘viewcontainer’, {‘read’: ViewContainerRef}) viewcontainer; Here, ViewContainerRef is a very important part, which makes the DOM node as a view container.

<>[email protected]({
  selector: 'app-root',
  template:`<span #el>I am manoj.</span>
  <span>I am a web developer.</span>`,
  styles:[`[highlight]{background: green; color: white}`]
})
export class AppComponent implements AfterViewInit{
  @ViewChild('el') span:ElementRef;

  ngAfterViewInit(){
    this.span.nativeElement.setAttribute('highlight', '');
  } 
}
<>[email protected]({
  selector: '[appHighlight]'
})
export class HighlightDirective implements OnInit{
  
  @Input() appHighlight;
  
  constructor( private element: ElementRef) { }
 
  ngOnInit(){
    this.element.nativeElement.setAttribute(this.appHighlight, '');
  }
}
<>[email protected]({
  selector: 'app-root',
  template:`<span [appHighlight]="'highlight'">I am manoj.<span>
  <span>I am a web developer.</span>`,
  styles:[`[highlight]{background: green; color: white;}`]
})
export class AppComponent{}
<>Copyconstructor( private element: ElementRef, 
private renderer: Renderer2) { }
 
ngOnInit(){
    this.renderer.setAttribute(this.element.nativeElement,this.appHighlight, '')
}
<>[email protected]({
  selector: 'app-parent',
  template: `<p>parent works!</p>
  <app-child #child></app-child>
  <button (click)='removeChild()'>remove child</button>`,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewChecked{

  @ViewChildren('child', {read: ElementRef}) childComp:QueryList<ElementRef>

  constructor(private renderer: Renderer2, private host: ElementRef) {
  }

  ngAfterViewChecked() {
    console.log(this.childComp.length)
  }

  removeChild(){
    this.renderer.removeChild(this.host.nativeElement, this.childComp.first.nativeElement);
  }
}
<>Copy<p>parent works!</p>
<ng-container #viewcontainer></ng-container>
<ng-template>
    <app-child #child></app-child>
</ng-template>
<button (click)='removeChild()'>remove child</button>
<>Copy  @ViewChildren('child', {read: ElementRef}) 
  childComp:QueryList<ElementRef>
  @ViewChild('viewcontainer', {'read': ViewContainerRef}) viewcontainer;
  @ViewChild(TemplateRef) template: TemplateRef<null>;

  constructor(private renderer: Renderer2, private host: ElementRef) {}

  ngAfterViewChecked() {
    console.log("Child components count", this.childComp.length)
  }

  ngAfterViewInit(){
    this.viewcontainer.createEmbeddedView(this.template);
  }

  removeChild(){
    this.viewcontainer.remove();
  }

Testing Angular Applications with Selenium Java

Step 2) Then, use executeAsyncScript () to wait 5 seconds. Step 3) Then, fetch the current time. Step 4) Subtract current time from start time which equals to passed time or output. Step 5) Verify

private static void setTimeout(int N) {    driver.manage().timeouts().implicitlyWait(seconds, TimeUnit.SECONDS);}
public static void WaitUntilVisible(WebElement element) {    waitForCondition(ExpectedConditions.visibilityOf(element), Config.elementWaitTimeout);}public static void waitBy(By by) {    WebDriverWait wait = new WebDriverWait(driver, 60);    wait.until(ExpectedConditions.visibilityOfElementLocated(by));}private static void waitForCondition(ExpectedCondition condition, int timeout) {    WebDriverWait wait = new WebDriverWait(driver, timeout);    wait.until(condition);}public static WebElement waitForElementToClickable(WebElement element) {    waitForCondition(ExpectedConditions.elementToBeClickable(element), Config.elementWaitTimeout);    return element;}
public String getRegionLabel() {    SeleniumUtils.WaitUntilVisible(regionLabel);    return this.regionLabel.getText();}
public static WebElement waitForVisibleFluentWait(WebElement element) {    final Wait<WebDriver> wait = getDefaultFluentWait()            .ignoring(NoSuchElementException.class)            .ignoring(ElementNotVisibleException.class);    wait.until(ExpectedConditions.visibilityOf(element));    return element;}private static FluentWait<WebDriver> getDefaultFluentWait() {    return getCustomFluentWait(DEFAULT_WAIT_TIME, DEFAULT_POLL_TIME);}private static FluentWait<WebDriver> getCustomFluentWait(int waitTime, int pollTime) {    return new FluentWait<>(driver)            .withTimeout(waitTime, TimeUnit.SECONDS)            .pollingEvery(pollTime, TimeUnit.SECONDS);}
import java.util.concurrent.TimeUnit;import org.openqa.selenium.JavascriptExecutor;		import org.openqa.selenium.WebDriver;		import org.openqa.selenium.firefox.FirefoxDriver;		import org.testng.annotations.Test;		    		public class AngularTest{@Testpublic void Login(){WebDriver driver= new FirefoxDriver();//Creating the JavascriptExecutor interface object by Type castingJavascriptExecutor js = (JavascriptExecutor)driver;//Launching the Site.driver.get("https://facebook.com/");//Maximize windowdriver.manage().window().maximize();//Set the Script Timeout to 20 secondsdriver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS);//Declare and set the start timelong start_time = System.currentTimeMillis();//Call executeAsyncScript() method to wait for 5 secondsjs.executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 5000);");//Get the difference (currentTime - startTime)  of times.System.out.println("Passed time: " + (System.currentTimeMillis() - start_time));}}
Passed time: 5022		PASSED: Login
JavascriptExecutor js = (JavascriptExecutor) driver;  js.executeScript(Script, Arguments);
//Click the elementpublic static void focusAndClick(WebElement element) {    JavascriptExecutor executor = (JavascriptExecutor) driver;    executor.executeScript("arguments[0].click();", element);}//Scroll the element into viewpublic static void scrollAndClick(WebElement element) {    JavascriptExecutor executor = (JavascriptExecutor) driver;    executor.executeScript("arguments[0].scrollIntoView(true);", element);    element.click();}//Scroll by specific amountpublic static Boolean scrollAndFind(WebElement element) {    JavascriptExecutor executor = (JavascriptExecutor) driver;    executor.executeScript("window.scrollBy(0,600);", element);    return element.isDisplayed();}//Scroll to the respective elementpublic static void scrollPage() {    JavascriptExecutor jse = (JavascriptExecutor) driver;    jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");}
<dependency>    <groupId>com.paulhammant</groupId>    <artifactId>ngwebdriver</artifactId>    <version>1.1.3</version></dependency>
WebDriver driver = new ChromeDriver();JavascriptExecutor jsDriver = (JavascriptExecutor) driver;NgWebDriver ngDriver = new NgWebDriver(jsDriver);
@BeforeMethodpublic void setUpClass() {    driver.get(TestUrls.url);    ngDriver.waitForAngularRequestsToFinish();}
driver.findElement(ByAngular.model("logIn")).click();
import com.paulhammant.ngwebdriver.ByAngularButtonText;public class LoginPage {    //Contains all the login page elements    private final WebDriver driver;@ByAngularButtonText.FindBy(buttonText = "Logout")   private WebElement logOut;public void logOut() {    dashboardPage.clickProfileIcon();    logOut.click();}}
<>[email protected]({
  ...
  template: `
    <button (click)="remove()">Remove child component</button>
    <a-comp></a-comp>
  `
})
export class AppComponent {}
<>[email protected]({...})
export class AppComponent {
  ...
  remove() {
    this.renderer.removeChild(
       this.hostElement.nativeElement,      // parent App comp node
       this.childComps.first.nativeElement  // child A comp node
     );
  }
}
<>[email protected]({
   …
   template: `<ng-container #vc></ng-container>`
})
export class AppComponent implements AfterViewChecked {
   @ViewChild('vc', {read: ViewContainerRef}) viewContainer: ViewContainerRef;
}
<>[email protected]({
  ...
  template: `
    <ng-template #tpl>
        <!-- any HTML elements can go here -->
    </ng-template>
  `
})
export class AppComponent implements AfterViewChecked {
    @ViewChild('tpl', {read: TemplateRef}) tpl: TemplateRef<null>;
}
<>[email protected]({ ... })
export class AppComponent implements AfterViewInit {
    ...
    ngAfterViewInit() {
        this.viewContainer.createEmbeddedView(this.tpl);
    }
}
<>[email protected]({ ... })
export class AppComponent implements AfterViewChecked {
  ...
  constructor(private r: ComponentFactoryResolver) {}
  ngAfterViewInit() {
    const factory = this.r.resolveComponentFactory(ComponentClass);
  }
 }
}
<>[email protected]({ ... })
export class AppComponent implements AfterViewChecked {
    ...
    ngAfterViewInit() {
        this.viewContainer.createComponent(this.factory);
    }
}
<>[email protected]({...})
export class AppComponent {
  show(type) {
    ...
    // a view is destroyed
    this.viewContainer.clear();
    
    // a view is created and attached to a view container      
    this.viewContainer.createComponent(factory);
  }
}
<>Copyshow(type) {
    ...
    // a view is destroyed
    this.viewContainer.clear();
    
    // a view is created and attached to a view container
    this.viewContainer.createEmbeddedView(this.tpl);
}
<>CopyaComponentFactory = resolver.resolveComponentFactory(AComponent);
aComponentRef = aComponentFactory.create(this.injector);
view: ViewRef = aComponentRef.hostView;
<>CopyshowView2() {
    ...
    // Existing view 1 is removed from a view container and the DOM
    this.viewContainer.detach();
    // Existing view 2 is attached to a view container and the DOM
    this.viewContainer.insert(view);
}
<>Copyview1: ViewRef;
view2: ViewRef;
ngAfterViewInit() {
    this.view1 = this.t1.createEmbeddedView(null);
    this.view2 = this.t2.createEmbeddedView(null);
}

NgModelChange and change in Angular with examples

In Angular, We will use ngModel for two way data binding.. Whenever a change happens in ngModel, Angular will trigger ngModelChange event.. ngModelChange is the @output property of ngModel directive. and it’s specific to Angular framework.. Where as (change) event is classic HTML DOM event, independent of Angular framework triggered when a change …

export class NgmodelchangeComponent implements OnInit {

  user = new User(); 

  userNamengmodelchange(value){
    console.log(value);
    console.log(this.user.Name)
  }

  phoneNumberngmodelchange(value){
    this.user.PhoneNumber = value;
    console.log(value);

  }

  constructor() { 
  }

  ngOnInit(): void {
  }

}

export class User{
  Name : string;
  PhoneNumber : Number;
}
User Name:<input [(ngModel)]="user.Name"/>
Phone Number:<input [(ngModel)]="user.PhoneNumber"/>

<p>User Name is {{user.Name}}</p>
<p>Phone Number is {{user.PhoneNumber}}</p>

export class NgModel extends NgControl implements OnChanges, OnDestroy {

  /**
   * @description
   * Event emitter for producing the `ngModelChange` event after
   * the view model updates.
   */
  @Output('ngModelChange') update = new EventEmitter();


  /**
   * @description
   * Sets the new value for the view model and emits an `ngModelChange` event.
   *
   * @param newValue The new value emitted by `ngModelChange`.
   */
  viewToModelUpdate(newValue: any): void {
    this.viewModel = newValue;
    this.update.emit(newValue);
  }

}  
<input [ngModel]="user.Name" (ngModelChange)="userNamengmodelchange($event)"/>

// In Component.ts file
userNamengmodelchange(value){
    console.log(value);          //Changed Value
    console.log(this.user.Name)  //undefined
}

// In Component.ts file
userNamengmodelchange(value){
    console.log(value);          //Changed Value
    console.log(this.user.Name)  //undefined
    this.user.Name = value;
}
<input [(ngModel)]="user.Name" (ngModelChange)="userNamengmodelchange($event)"/>

// In Component.ts file
userNamengmodelchange(value){
    console.log(value);          //Changed Value
    console.log(this.user.Name)  //Changed Value
}
<input [ngModel]="user.Name"
       (ngModelChange)="user.Name = $event" 
       (ngModelChange)="userNamengmodelchange($event)"/>
<input [ngModel]="user.Name"
       (ngModelChange)="userNamengmodelchange($event)"/>

userNamengmodelchange(value){
    console.log(value);          //Changed Value
    console.log(this.user.Name)  //undefined
    this.user.Name = value; // Update the value here
}
<input [ngModel]="user.Name"
       (ngModelChange)="user.Name = $event" 
       (ngModelChange)="userNamengmodelchange($event)"
       (ngModelChange)="userNamePrint()" />

//in the component.ts file
userNamePrint(){
    console.log('userNameprint()');
}

User Name: <input (change)="changeUserName($event)"/>


changeUserName(e) {
    console.log(e);
    this.user.Name = e.target.value;
}

User Name: <input (change)="changeUserName($event)" 
                  (ngModelChange)="userNamePrint()"/>


changeUserName(e) {
    console.log(e);
    this.user.Name = e.target.value;
}


User Name: <input [ngModel]="user.Name" 
                  (change)="changeUserName($event)" 
                  (ngModelChange)="userNamePrint()"/>


changeUserName(e) {
    console.log(e);
    this.user.Name = e.target.value;
}

Previous PostNext Post

Related code examples