Display or conceal password text with Nativescript

I am working on a login form where I need to toggle the visibility of the password text. Below is the code snippet that I have implemented.

Here is the code I tried:

    <GridLayout margin="10" verticalAlignment="center" backgroundColor="#ffffff">
        <StackLayout margin="10" verticalAlignment="center" [formGroup]="signUpForm" padding="15">
            <StackLayout class="input-field">
                <TextField formControlName="username" hint="Username"></TextField>
            </StackLayout>
            <StackLayout class="input-field">
                <TextField formControlName="password" hint="Password" secure="true">
                </TextField>
            </StackLayout>
            <Label text ="show/hide" (tap)="toggleShow()"></Label>
        </StackLayout>
   </GridLayout>

In my component.ts file, I have written the following code:

export class LoginComponent implements OnInit {
    signUpForm: FormGroup;
    show = false;
    type=  'password';
    constructor(....) {
        this.signUpForm = this.formBuilder.group({
            username: ["", Validators.required],
            password: ["", Validators.required]
        });
    }
    toggleShow()
    {
        this.show = !this.show;
        if (this.show){
            this.type = "text";
        }
        else {
            this.type = "password";
        }
    }
}

After clicking the toggleShow() function and checking in the console with console.log(this.show), the output shows true/false, but nothing changes in the template. Can you suggest any ideas or point me to what might be wrong in my code?

Thank you!

Answer №1

UPDATE: A user named SeanStanden has shared an improved solution that should now be considered the accepted answer.

In my opinion, it would be more beneficial to adjust the secure property on the Textfield using element references:

.ts:

export class HomeComponent {
    @ViewChild('passwordField') passwordField: ElementRef;

    constructor() { }

    toggleVisibility() {
        console.log(this.passwordField.nativeElement.secure);
        this.passwordField.nativeElement.secure = !this.passwordField.nativeElement.secure;
    }
}

.html:

<GridLayout margin="10" verticalAlignment="center" backgroundColor="#ffffff">
    <StackLayout margin="10" verticalAlignment="center" padding="15">
        <StackLayout class="input-field">
            <TextField hint="Username"></TextField>
        </StackLayout>
        <StackLayout class="input-field">
            <TextField #passwordField hint="Password" secure="true">
            </TextField>
        </StackLayout>
        <Label text="Toggle Visibility" (tap)="toggleVisibility()"></Label>
    </StackLayout>
</GridLayout>

Check out the example playground for demonstration:

Answer №2

Instead of accessing the native element directly, you can simply bind to the 'secure' property and toggle it easily:

<StackLayout class="input-field">
   <TextField formControlName="password" hint="Password" [secure]="securePassword">
   </TextField>
</StackLayout>
<Label text ="show/hide" (tap)="toggleShow()"></Label>

TS

toggleShow() {
  this.securePassword = !this.securePassword;
}

Answer №3

If you're using NativeScript-Vue and need an additional tip based on Sean's answer, here it is:

<TextField class="input" :text="password" :secure="securePassword" ></TextField>

<Label class="passmsg" :text="passmsg" @tap="toggleShow()"></Label>

Within your methods:

toggleShow () {
  this.securePassword = !this.securePassword
  if (this.securePassword) this.passmsg = 'Show Password'
  else this.passmsg = 'Hide Password'
}

Remember to include passmsg in your data section.

Answer №4

Update your code with the changes provided below.

<StackLayout class="input-field">
    <TextField formControlName="password" [hint]="passwordType" secure="true"></TextField>
</StackLayout>

TypeScript:-

passwordType: string = "password";
toggleShow()
    {
        this.passwordType = (this.passwordType == "password") ? "text" : "password";
    }

I hope this information is helpful to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered difficulties implementing Chart.js with Angular2

Greetings! I am currently attempting to utilize one of the Charts provided by http://www.chartjs.org, however, I seem to be encountering difficulties in getting it to function properly. I have followed the documentation by installing 'npm install char ...

Angular class mapping of web API response

I have a web API action method that returns a chapter ID and chapter name. I would like to convert this into an Angular class with an additional field called 'Edit', which by default is set to false. export class Chapter { chapterid: number; ...

Creating an Object Type from a String Union Type in TypeScript

How can I go about implementing this? type ActionNames = 'init' | 'reset'; type UnionToObj<U> = {/* SOLUTION NEEDED HERE */} type Result = UnionToObj<ActionNames>; // Expected type for Result: `{ init: any, reset: any }` ...

Here's a unique version of the text: "Tips for clearing up opacity in a Highchart bar

When dealing with a large dataset, I am utilizing the scroll in a bar chart using the Highcharts library. However, I noticed that as users scroll up or down, some data are becoming hidden within the scroll. Is there a way to remove the opacity when using t ...

Encountering TypeScript error while utilizing Vue.mixin in Vue framework

I am currently developing an SSR application using Vue.js. During my development process, I encountered a TypeScript error while attempting to do this. Vue.mixin({ beforeRouteUpdate (to, from, next) { const { asyncData } = this.$options ...

Ways to restrict access for non-authorized individuals to view pictures stored in Firebase Storage

Our application allows users to upload images using AngulrFirestore, which are then saved in Firebase storage. When the file is uploaded, we receive a DownloadURL and save it in a firestore document for the respective object. However, we have encountered ...

Compulsory selection and input fields in Angular forms

I need the select and input fields of the form to be required. I attempted to follow the angular website tutorial, but it didn't work for me or I might have made a mistake. How can I resolve this issue? Below is my HTML file: <form [formGroup]="a ...

Assign a value to a variable using a function in Typescript

Is there a way in typescript to explicitly indicate that a function is responsible for assigning value to a variable? UPDATED CODE Here, the code has been simplified. While getText() ensures that it will never be undefined, this may not hold true in subs ...

"Utilize XML parsing to convert data into JSON format and set up subscription functionality

My current task involves converting an XML string to JSON using xml2js. I then need to send and subscribe to the result in another component. getLastWeekSnow = function(){ let headers = new Headers(); headers.append('Access-Control-Allow-Origin' ...

"Troubleshooting: Issue with angular-in-memory-web-api unable to locate newly

I am currently working on an Angular 2 project that involves a Node.js backend. My goal is to utilize the angular-in-memory-web-api to access a database created within a custom file named "./in-memory-data-service,". This process closely follows the Tour o ...

Is it possible to modify the stroke color of the progress circle in ng-zorro?

I am working on an Angular project where I aim to create a dashboard displaying various progress circles. Depending on the progress, I need to change the color of the line. Current appearance: https://i.sstatic.net/hR2zZ.png Desired appearance: https://i. ...

Guide to updating the file name while downloading in JHipster (Java and Angular)

Here is the snippet of code responsible for opening the file from the controller: openFile(contentType, field) { return this.dataUtils.openFile(contentType, field); } Within the HTML, this function is used to pass in data retrieved from a servic ...

Adding a custom source to the script tag in Angular 7

I am currently using angular cli to develop my web application. The app is being built in the dist folder as of now. This is the index.html file: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Adm ...

Is it possible for a node and @angular/cli based application to function without an internet connection?

As a newcomer to the world of angular/cli and node, I am eager to build an application using Angular and deploy it to an environment where all external communication is blocked by a firewall. In this restricted setting, even accessing search engines is imp ...

Iterating through a JSON object to verify the presence of a specific value

I have a JSON Object and I am looking for a way in Angular 6 to search for the value "Tennis" in the key "name". Can you provide guidance on how to achieve this? { "id":2, "name":"Sports", "url":"/sports" "children":[ { "id":1, ...

Erase Typescript Service

To remove a PostOffice from the array based on its ID, you can use a checkbox to select the desired element and then utilize its ID for the delete function. Here is an example: let postOffices = [ {postOfficeID: 15, postCode: '3006&ap ...

Setting up React Context API with TypeScript: A Step-by-Step Guide

I recently updated my app.js file to app.tsx for improved functionality. However, I encountered an error with the current value. app.tsx import React, { createContext, useState } from "react"; import SelectPage from "./pages/select/select& ...

Ways to boost performance in an Angular 6.0 application

https://i.stack.imgur.com/Rq9Y2.jpg We have recently developed a cutting-edge application using Angular 6, hosted on an Apache 2.4 server. To ensure our website is properly crawled by search engines, we set up a local "prerender" instance. Initially, we t ...

Building a React TypeScript project is successful on Windows, but encounters issues when attempted on a

Currently, I am immersed in a project that involves React TypeScript. Here is the content of the package.json: { "version": "0.1.0", "private": true, "dependencies": { ///... "react": "^16.8.6", "react-scripts-ts": "3.1.0", }, "scri ...

How to apply CSS classes to dynamically injected HTML in Angular 7

One of the challenges I'm currently facing is how to assign a CSS class based on a calculation in my component. Here's a snippet from my component class: @Component({ selector: 'app-render-json', template: `<div [innerHtml ...